实体框架 4 - 如何更新对象
NET 4 和 C#。
我有一个对象 (myContentObj) 和一个导航属性 (CmsGroupsTypes)。
我需要更新特定对象的导航属性。
目前,我使用下面的代码删除当前关联并添加一个新关联,以便我可以更新导航属性。
尽管我的代码有效,但我想知道您是否知道更好的方法...我不确定 EF4 中是否存在 UPDATE 方法或类似方法。
感谢您的帮助!
// Remove object
myContentObj.CmsGroupsTypes.Remove(myCurrentGroupTypeObj);
// Update object
myContentObj.CmsGroupsTypes.Add(myNewGroupTypeObj);
context.SaveChanges();
net 4 and c#.
I have an Object (myContentObj) and a navigational property (CmsGroupsTypes).
I need update the navigational property for specific objct.
At the moment I use this code below to remove the current association and add a new one, so I can Update the navigational property.
Albeit my code works, I would like to know if you know a better approach to it... I am not sure if exist an UPDATE method or similar in EF4.
Thanks for your help!
// Remove object
myContentObj.CmsGroupsTypes.Remove(myCurrentGroupTypeObj);
// Update object
myContentObj.CmsGroupsTypes.Add(myNewGroupTypeObj);
context.SaveChanges();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是正确的做法。您正在修改导航属性=您正在修改实体之间的关系。要删除实体之间的关系,您必须从导航属性中删除相关实体。要添加实体之间的关系,您必须将相关实体添加到导航属性。
唯一的问题可能是,如果您使用数据库中存在的实体调用
Add
,但该实体未从数据库加载(虚拟对象或分离实体)。在这种情况下,EF 将尝试再次将您的实体插入数据库。为了避免这种情况,您必须使用附加实体(从数据库加载它)或将其状态设置为Unchanged
。另一种方法是使用外部关联,其中依赖实体也提供外键属性。您只需将此属性设置为父级的 id 即可更改关系。这仅适用于一对一和一对多关系。
请注意,从父级导航属性中删除实体不会从数据库中删除子实体。因此,如果与父级的关系是依赖的,您还必须删除它,否则 SaveChanges 会抛出异常。
This is the correct approach. You are modifying a navigation property = you are modifying a relation between entities. To remove the relation between entities you must remove the related entity from the navigation property. To add the relation between entities you must add the related entity to the navigation property.
The only issue can be if you call
Add
with an entity which exists in DB but it is not loaded from the database (a dummy object or a detached entity). In this case EF will try to insert your entity to the database again. To avoid that you must either use an attached entity (load it from DB) or set its state toUnchanged
.Other way is using foreign association where a dependent entity also offers a foreign key property. You can change relation simply by setting this property to id of the parent. This is usable only for one-to-one and one-to-many relations.
Be aware that removing the entity from the parent's navigation property doesn't delete entity the child entity from database. So if the relation to parent is dependent you must also delete it or
SaveChanges
throws exception.Context 跟踪您的对象,只需从 context 获取它,更改其数据和 Context.SaveChanges()
Context keeps track of your objects, just get it from context, change its data and Context.SaveChanges()
我对此不太确定,现在也无法检查,但我认为您可以直接更改
myCurrentGroupTypeObj 属性,然后
我希望它能起作用。如果没有,请告诉我。
I'm not really sure about this, and I can't check it right now, but I think you can directly change the
myCurrentGroupTypeObj properties, and then do
I hope it works. If not, please let me know.