我有一个带有int值的数组,表示ID
我有一个实体(用EF生成),其中一个集合属性代表一个相关的表(1到n)
我需要使用数组中的值更新此集合
当然我可以预先解决那个问题,但我确信有更好的方法可以与Linq做到这一点吗?
谢谢
I have an array with int values which represents ID
I have an entity (generated with EF) with a collection property wich represents a related table (1 to n)
I need to update this collection with the values in the array
Of course I can foreach the one then the seconde but I'm sure there is a better way to do that with Linq maybe ?
Thanks
最满意答案
据我所知,EF中没有“一步”更新命令。 首先,您必须选择您的项目,然后更改它的值,然后保存它。 2分贝往返(选择并保存)。
但是,如果您的ID列是主键或唯一,那么对于每个项目,创建新的db对象,设置ID值并附加它(使用attach方法),更改值并保存。 1分贝往返(只需保存)。 我更喜欢这个以提高性能。
另一方面,有一个用于一步更新命令的开源库。 但他们只支持SQL Server。 我记不起图书馆的名字了。
附加示例:
using (DataEntities context = new DataEntities()) { foreach (int ID in IDList) { TableName item = new TableName(); item.ID = ID; context.TableName.Attach(item); item.IsDeleted = true; //Change a filed's value } context.SaveChanges(); }There is no "one step" update command in EF, as far as I know. First you have to select your item, then change it's value and then save it. 2 db round trip (select and save).
But if your ID column is primary key or unique, then for every item, create new db object, set ID value and attach it (use attach method), change value and save it. 1 db round trip (just save). I prefer this for performance increase.
On the other hand, there are two open source library for one step update command. But they only support Ms SQL Server. I couldn't remember the names of the libraries.
Example for attach:
using (DataEntities context = new DataEntities()) { foreach (int ID in IDList) { TableName item = new TableName(); item.ID = ID; context.TableName.Attach(item); item.IsDeleted = true; //Change a filed's value } context.SaveChanges(); }更多推荐
发布评论