gpt4 book ai didi

c# - 通过 LINQ to SQL 中的新对象更新实体

转载 作者:太空宇宙 更新时间:2023-11-03 16:53:43 25 4
gpt4 key购买 nike

我想通过 linq 更新一个实体,但由于我在序列化后在 View 中编辑实体,所以我无法直接访问数据上下文中的实体。我可以这样做:

entity.property1 = obj.property1;
entity.property2 = obj.property2;
...

那不酷……一点也不酷。

接下来我尝试的是像这样通过 .attach() 来完成它:

context.Table.attach(entity, obj);

也不行。那么除了反射(reflection)还有其他选择吗?

最佳答案

Attach() 不工作,因为实体仍然附加到 DataContext。您是否考虑过在重新附加实体时创建 DataContext 的新实例?通常建议不要使用长期存在的 DataContext,而应该为每个工作单元创建一个新实例。这是因为只要您将 DataContext 实例保留在内存中,您从中检索到的所有实体也会保留在内存中(假设启用了 ObjectTracking)。

来自 MSDN:

In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.

http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx

关于c# - 通过 LINQ to SQL 中的新对象更新实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2952967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com