在什么情况下我需要实体框架中的外键和导航属性 [英] In what scenarios do I need foreign keys AND navigation properties in entity framework

查看:37
本文介绍了在什么情况下我需要实体框架中的外键和导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Order 类有:

My Order class has:

public int CustomerId { get; set; }

public Customer Customer { get; set; }

我真的需要这两个属性来建立关系吗?

Do I really need both properties to make a relation working?

我没有使用断开连接的实体,我使用的是代码优先方法.

I am not using disconnected entities, I am using code first approach.

推荐答案

根据 Julia Lerman 的书:编程实体框架:DbContext,区别在于更新导航属性的难度.在第 85 页,她建议如果您可以做一件事来让您在 N 层场景中的生活更轻松,那就是为模型中的关系公开外键属性."本书包含两种场景的示例.

According to Julia Lerman's book: Programming Entity Framework: DbContext, the difference lies at the difficulty of updating the navigation property. In page 85, She suggests "If there is one thing you can do to make your life easier in N-Tier scenarios, it’s to expose foreign key properties for the relationships in your model." The book includes samples for both scenarios.

原因是包含一个外键属性告诉实体框架使用外键关联,这比在需要更新关系时使用所谓的独立关联更简单,即将订单从一个客户更改为另一个客户在你的例子中.使用外键关联,您需要做的就是更改 CustomerId.如果没有 CustomerId 外键,您需要更多步骤.独立关联使用 ObjectStateManager 说明 Code First: Independent associations vs.外键关联? ObjectStateManager 很复杂,甚至没有从 DbContext API 中公开.

The reason is that including a foreign key property tells Entity Framework to use Foreign Key Association, which is simpler than using the so-called Independent Association when you need to update the relationship, i.e., changing the order from one customer to another in your example. With foreign key association, all you need to do is changing the CustomerId. Without the CustomerId foreign key, you need more steps. The independent association uses the ObjectStateManager that is explained Code First: Independent associations vs. Foreign key associations? The ObjectStateManager is complex and is not even exposed from DbContext API.

这篇关于在什么情况下我需要实体框架中的外键和导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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