有外键和导航属性立即同步 [英] Have the foreign key and navigation property synced immediately

查看:196
本文介绍了有外键和导航属性立即同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



$ $ 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.

这篇关于有外键和导航属性立即同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆