实体框架 4.1.代码优先 - 在模型中显式使用外键

发布于 2024-12-18 02:32:09 字数 157 浏览 5 评论 0原文

目前我的模型都有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹿! 2024-12-25 02:32:09

您不需要显式声明外键。默认情况下,EF 代码首先将创建与对象引用的一对一关系以及与对象引用集合的一对多关系。唯一需要的是主 ID。

现在,当必须映射到特定字段或想要使用外键而不包含关系时,显式声明外键可能会很方便。在我的一个项目中,我还威胁我的实体(在你的例子中是模型)作为 DTO 的。因此我不希望存在关系。我使用显式外键加载其他数据,例如:

var student = service.GetStudent();
var class = service.GetClassById(student.ClassId);

这完全取决于实际需求,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:

var student = service.GetStudent();
var class = service.GetClassById(student.ClassId);

It all depends on the requirements really and EF code first gives you a fine toolset of realizing what you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文