实体框架 4.1.代码优先 - 在模型中显式使用外键
目前我的模型都有一个 Id(主键),但是对其他模型的引用是在不使用数字 ID 的情况下进行的,即它们是对象引用。我期待 EF 提供魔力,让这项工作如我所愿......目前看来正是如此。但是,我看到很多带有显式整数外键的问题和示例。我是否遗漏了某些东西或对框架期望过高 - 或者这就是它的设计使用方式?
My models at the moment have all have an Id (primary key), but references to other models are made without use of numerical ids ie they are object references. I am expecting EF to supply the magic to make this work as I expect.. which it seems to be at the moment. However, I see a lot of questions and examples with explicit integer foreign keys. Am I missing something or expecting too much from the framework - or is this how its designed to be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要显式声明外键。默认情况下,EF 代码首先将创建与对象引用的一对一关系以及与对象引用集合的一对多关系。唯一需要的是主 ID。
现在,当必须映射到特定字段或想要使用外键而不包含关系时,显式声明外键可能会很方便。在我的一个项目中,我还威胁我的实体(在你的例子中是模型)作为 DTO 的。因此我不希望存在关系。我使用显式外键加载其他数据,例如:
这完全取决于实际需求,EF 代码首先为您提供了一个很好的工具集来实现您的需求。
You dont need to declare foreign keys explicitly. By default, EF code first will create a one to one relationship with an object reference and a one to many relationship with a collection of object references. The only thing that is required is a primary id.
Now declaring foreign keys explicitly might be convenient when having to map to a specific field or when wanting to work with foreign keys without including the relationships. In a project of mine, i also threat my entities (models in your case) as DTO's. Therefore i dont want relationships to exist. I use explicit foreign keys to load in other data like:
It all depends on the requirements really and EF code first gives you a fine toolset of realizing what you need.