I am accessing a database using LINQ, and making changes to the records. I retrieve the records like so:
using(var db = new DatabaseDataContext(connectionString))
{
var query =
from item in db.table
where item.senddate == null
select item;
results = query.ToList();
}
After getting the items, I process each one, which requires communication with a web service, and can take more than a minute per record. When the record has been updated, I need to submit the changes, but I am not sure how to proceed. Currently, I do the following:
List<table> toProcess = QueryDb(); // Calls the previously displayed method
foreach (table item in toProcess)
{
item.result = QueryDb(item.xmlrequest);
PostToDb(item);
}
...
private bool PostToDb(table submit)
{
submit.senddate = DateTime.Now;
using (var db = new DatabaseDbDataContext(connectionString))
{
db.SubmitChanges();
}
return result;
}
db.SubmitChanges()
does not submit any changes, but I haven't really set that the object "submit" holds the changes. How do I submit the changes made to the entry without keeping the Db connection open for several minutes while the files are processed one at a time?
Thank you in advance for any assistance.
I don't think this is the best solution, but I was able to get it to work with the following changes to my code:
private bool PostToDb(table submit)
{
using (var db = new DatabaseDataContext(connectionString))
{
var query =
from item in db.table
where item.iprimaryid.Equals(submit.iprimaryid)
select item;
// There can only be one result, but this was the only
// way I could think to access it
foreach (var item in query)
{
item.senddate = DateTime.Now;
item.result = submit.result;
}
db.SubmitChanges();
}
return result;
}
You need to use the Attach
method for your DataContext
. So, your steps are:
1) Query object from the database using one instance of your DataContext
2) Make some changes
3) Create the new DataContext
instance and attach modified entities.
using (var dataContext = new DataContext(ConnectionString))
{
dataContext.TABLE_NAME.Attach(modifiedEntity);
dataContext.SubmitChanges();
}