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

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

问题描述

我的订单类有:

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 代码第一:独立的关联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天全站免登陆