EF: Eliminating Multiple Update Operators

Code like this:

var compIds = from p in packinglist.List select p.ComponentId; var components = from c in context.Components where compIds.Contains(c.Id) select c; foreach (var item in components) { item.CurrentSiteId = packinglist.DestinationId; } context.SaveChanges(); 

Finishes releasing a variety of SQL statements, such as

 update [dbo].[Components] set [CurrentSiteId] = @0 where ([Id] = @1) 

Is there a way to instruct EF (Code First) about the following:

 update [dbo].[Components] set [CurrentSiteId] = @0 where ([Id] in (....)) 

Or should I learn to use one of the available SQLQuery methods or a standalone tool like Dapper or an array or ...?

+4
source share
2 answers

There is currently no way to perform bulk updates in EF 4 out of the box. There is a very long complicated job that ultimately leads to the creation of SQL. I suggest using a stored procedure or T-SQL. Here is a quick T-SQL snippet I used in the past:

 using (var context = new YourEntities()) { context.ExecuteStoreCommand( @"UPDATE Components SET CurrentSiteId = 1 WHERE ID IN(1,2,3,4)"); } 
+2
source

The simplest answer is to simply write this query and use DbContext.SQLQuery() to run it. As mentioned, there is no way in EF to do this.

0
source

All Articles