EF Linq:使用Array中的ID更新相关表List(EF Linq : Update related table List with ID in Array)

编程入门 行业动态 更新时间:2024-10-26 11:24:18
EF Linq:使用Array中的ID更新相关表List(EF Linq : Update related table List with ID in Array)

我有一个带有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(); }

更多推荐

本文发布于:2023-07-26 03:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1270690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Array   ID   EF   Linq   related

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!