简体   繁体   中英

Linq to SQL update multiple records in one query

Given the code:

var q = db.TranslationProjectKeys.Where(c => c.ProjectID == forProject.ID);
foreach (var key in q)
{
    key.Live = false;
}
db.SubmitChanges();

If I run the SQL server profiler it shows dozens of UPDATE.... SQL statements. I believe this would be considerably faster if this query was executed with one UPDATE statement:

UPDATE TranslationProjectKeys SET Live = 0 WHERE ProjectID = x

Is there a way to make the query execute in this way?

I'm wary of using db.ExecuteCommand("...") as I am aware the context can be cached which can cause some bugs.

You can use EntityFramework.Extended . You can execute multiple update. For Example

var q = db.TranslationProjectKeys.Where(c => c.ProjectID == forProject.ID).Update(c => new TranslationProjectKey{ Live  = false })

linq to sql does not have a built in mass update function (unless something has changed). you could just execute the command manually like

dataContext.ExecuteCommand("UPDATE TranslationProjectKeys SET Live = 0 WHERE ProjectID = {0}", x);

or if you wanted to get fancy, you could try implementing your own mass update functionality like this article shows, but it is MUCH more in depth and complicated (Though it IS possible to do)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM