Reuse query SqlExpression cause System.ArgumentException The SqlParameter is already contained by another SqlParameterCollection - ormlite-servicestack

With OrmLite ServiceStack, I did query Select list and Count total like this:
public async Task<OrmInvoice> OrmTest(int Id)
{
var q = OrmDb.From<OrmInvoice>().Where(o => o.Id == Id);
var rs1 = await OrmDb.SelectAsync(q);
var rs2 = await OrmDb.CountAsync(q);
var q2 = q.Clone(); //try to clone
var rs3 = await OrmDb.CountAsync(q2);
return null;
}
i tested with only rs1 and rs2 => error
try to Clone , rs3 => same error
Caught System.ArgumentException
System.ArgumentException: The SqlParameter is already contained by another SqlParameterCollection.
at System.Data.SqlClient.SqlParameterCollection.Validate
at System.Data.SqlClient.SqlParameterCollection.Add
at ServiceStack.OrmLite.OrmLiteReadCommandExtensions.SetParameters
I'm stuck and don't know why this issue occurs, from base of ormlite ? Thanks for your help!

You should clear parameters before the second query.

Related

How can i Insert into one table and Update another table using Linq

I have the following linq expression, I am trying to create a new record in to address table and Update customer table with the newly created AdressID, How can i create a new address get the new AddressID and update customer table
if (request == null)
throw new ArgumentNullException(nameof(request));
if (request.AddressToCreate == null)
throw new ArgumentNullException(nameof(request.AddressToCreate));
var address = Mapper.Map<Address>(request.AddressToCreate);
address.CreatedBy = request.AddressToCreate.CreatedBy;
address.CreatedDate = SystemClock.UtcNow;
address.UpdatedBy = request.AddressToCreate.UpdatedBy;
address.UpdatedDate = SystemClock.UtcNow;
await Context.AddAsync(address);
var rps = Context.Customers .Where(rc => rc.ID == request.ID).SingleOrDefault();
rps.AddressID = request.AddressToCreate.ID;
await Context.SaveChangesAsync();
But request.AddressToCreate.ID; returns 0, How can i modify my code to get the New AddressID
I would recommend this:
Firstly you may not have an Id property to your AddressToCreate.
Secondly AddAsync() may not call Context.SaveChangesAsync() so the entity is not commited to database and the id is 0.
Try it like this;
await Context.AddAsync(address);
await Context.SaveChangesAsync(); // this is optional only if you have modified AddAsync() and it doesnt call SaveChangesAsync inside
var rps = Context.Customers.FirstOrDefault(rc => rc.ID == request.ID);
rps.AddressID = address.ID;
await Context.UpdateAsync(rps);
await Context.SaveChangesAsync();

Problems with IDocumentQuery.ExecuteNextAsync()

I have standard lines of code, to fetch data with pagination. It used to work until a month ago, and then stopped. On running ExecuteNextAsync() it stops execution, and displays this following information in Output window:
DocDBTrace Information: 0 : DocumentClient with id 2 disposed.
DocDBTrace Information: 0 : DocumentClient with id 1 disposed.
Not Working Code:
var query =
client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri(databaseId, "TestCollection"), "select c.id from TestCollection c",
new FeedOptions
{
//MaxDegreeOfParallelism=-1,
MaxItemCount = maxItemCount,
PopulateQueryMetrics=true
//RequestContinuation = requestContinuation,
//EnableScanInQuery = true,
//EnableCrossPartitionQuery = true
});
var queryAll = query.AsDocumentQuery();
var results = new List<TDocument>();
while (queryAll.HasMoreResults)
{
try
{
var result = await queryAll.ExecuteNextAsync();
var queryMetrics = result.QueryMetrics;
if (result.ResponseContinuation != null) requestContinuation = result.ResponseContinuation;
//Do something here
}
catch (Exception ex)
{
}
}
For the same client object, Create/Update or fetching all items together is working. So JsonSerializer or DocumentClient object cannot be a problem.
Working code:
var query2 = client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri(databaseId, collectionName), "select * from TestCollection c",
new FeedOptions { MaxItemCount = -1 });
//.Where(l => l.Id == qId);
var testData2= query2.ToList();
This has stopped our services and their development. Any help is appreciated.
Your query is wrong.
UriFactory.CreateDocumentCollectionUri(databaseId, "TestCollection") will already let the SDK know what to query.
If you simply change
select c.id from TestCollection c
to
select c.id from c
It will work. Currently it is failing to resolve the c alias because you also have TestCollection there.
The only reason your other queries that use * are working is because you aren't using the c. there.

functions.database.ref & Auto ID

able to get function.database.ref to work for basic chains like this.
functions.database.ref("/following/{uid}/{followingId}").onCreate(event => {
var uid = event.params.uid;
var fromId = event.params.fromId
however I have no idea what to do when we are creating something with an autoId that has a sub branch in this case fromId.
exports.NewActMessage = functions.database.ref("/ActPosts/{uid}/messages/autoId/{fromId}").onCreate(event => {
var uid = event.params.uid; //JOSIAH SAVINO
var fromId = event.params.fromId
Whats even more challenging is the autoId is what is being created but I need to pull the "fromId" information from the branch inside of the autoId.
image
Firebase messaged me how to get first the autoId than the fromId from that like so...
exports.NewActMessage =
functions.database.ref('/ActPosts/{uid}/messages/{autoId}').onCreate(event => {
var uid = event.params.uid;
var autoId = event.params.autoId;
var fromId = event.data.val().fromId;

.NET Already Open DataReader

I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)

Linq update record

How do you update a record with a specific ID in LINQ to SQL (ASP.Net / C#)?
You can do it like this...
var record =
(
from x in db.TableName
where x.Id == 12345
select x
)
.Single();
record.DateUpdated = DateTime.Now;
db.SubmitChanges();
Hope it helps :)
Care to post some sample code you've taken a stab at.
If it's linq2sql, then it should be a simple matter of Retrieving your object using your linq datacontext using a Where<T>() clause , updating the object property and then calling the DataContext.SubmitChanges()
Look at this piece of code for example.
void UpdateRow(Int32 intID)
{
bool IsSuccessfullyUpdated = false;
var db = new DataContext();
try
{
var dbCstInfo = db.TableName
.Where(w => w.ID == intID)
.SingleOrDefault();
if (dbCstInfo != null)
{
dbCstInfo.IsActive = !dbCstInfo.IsActive;
dbCstInfo.Name = "BJP";
dbCstInfo.Comp = "PVtal";
db.SubmitChanges();
IsSuccessfullyUpdated = true;
}
}
catch
{
IsSuccessfullyUpdated = false;
}
return IsSuccessfullyUpdated;
}

Resources