有外键和导航属性立即同步

编程入门 行业动态 更新时间:2024-10-25 15:35:07
本文介绍了有外键和导航属性立即同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

$ $ p $ $ code $ public $ $ $ $ $ {$ b $ key $ b $ public int ModelId {get;组; } public string Name {get;组; } public virtual Model Other {get;组; } [ForeignKey(Other)] public int OtherId {get;组; } //其他常规映射的属性不显示}

我使用EF 6.1.3 Code First。我需要这个,因为我的UI网格控件只改变ID(改变导航对象在这里导致麻烦),但我的业务逻辑在保存记录之前,需要在ID改变之后立即要求引用对象的信息。被引用的对象的数据决定了用户必须编辑记录的其他选项。

这个问题回答了我的问题:

所有映射的属性必须是虚拟的。一旦一个映射的属性不是虚拟的,整个事情就不会再起作用了,没有人告诉你。

我还没有看到一个简单的方法来验证这是完成的,但如果这样做,实体框架将应用一些更有效的更改跟踪,这也有外键属性更新导航属性的效果,反之亦然。 哦,这只适用于实体框架代理类。查询现有对象时,或使用 DbSet.Create()方法获得这些信息。直接创建模型类的新实例不会自动执行任何操作。

What do I have to do to have Entity Framework immediately sync the foreign key and the navigation property whenever either is changed, not just after calling SaveChanges?

public class Model { [Key] public int ModelId { get; set; } public string Name { get; set; } public virtual Model Other { get; set; } [ForeignKey("Other")] public int OtherId { get; set; } // Other regular mapped properties not shown }

I'm using EF 6.1.3 Code First. Change tracking is not explicitly deactivated and should be used.

I need this because my UI grid control changes the ID only (changing navigation object here causes trouble) but my business logic requires information from the referenced object immediately after the ID was changed, before saving the record. The referenced object's data determines what other options the user has to edit the record.

解决方案

It seems that this question answers my question:

All mapped properties must be virtual. As soon as a single mapped property is not virtual, the whole thing doesn't work anymore and nobody tells you.

I haven't seen an easy way to verify that this is done, but if it is done, Entity Framework will apply some "More efficient change tracking" which also has the effect of foreign key properties updating navigation properties, and vice versa.

Oh, and this only works with Entity Framework proxy classes. You get these when querying existing objects, or with the DbSet.Create() method. Creating new instances of the model class directly won't do anything automatically.

更多推荐

有外键和导航属性立即同步

本文发布于:2023-11-12 01:00:24,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   有外键

发布评论

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

>www.elefans.com

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