patterncsharpMinor
Update multiple records with Entity Framwork
Viewed 0 times
updatewithrecordsframworkmultipleentity
Problem
I am wondering what the best way to update multiple records with Entity Framework is.
This is how I normally do it, and it does work:
This query should also work (is one better than the other)
Another way could be looping through the
This is how I normally do it, and it does work:
private static void SetNcprpCodesAsComplete(string[] ncprpCodes)
{
using (var ent = new Data.Entities())
{
var query = from ba in ent.BuildingAssessments
where ncprpCodes.Contains(ba.NcprpCode)
select ba.TabletAssessment;
foreach (var ta in query) ta.Complete = true;
ent.SaveChanges();
}
}This query should also work (is one better than the other)
var query = from ta in ent.TabletAssessments
where ncprpCodes.Contains(ta.BuildingAssessment.NcprpCode)
select ta;Another way could be looping through the
string[], attaching and updating. Is it possible to attach when doing a multi table query like this?Solution
This is the usual way how to update properties in EF, and in your case, I'd say it seems the only proper way. You can surely attach and update - but then you'll loose all other properties in your entity. To sum up - if you'd need to update one property in entities, you'll need to do SELECT (your query), modify entities (foreach) and then do UPDATE (SaveChanges).
Context
StackExchange Code Review Q#55861, answer score: 7
Revisions (0)
No revisions yet.