实体框架中与查找表的多种关系
问题的上下文是 ASP.NET MVC2 / EF4。我在数据库中有许多查找表,这些表以前已以编程方式引用,每个表都来自许多其他表...因此可能有一个包含国家/地区 ID 短代码、desc 的国家/地区表,以及六个具有乡村在他们身上。对 5 或 6 个其他查找表重复此操作。目前还没有 FK - 查找已在旧数据库前端的 UI 中以编程方式进行。
另一件需要警惕的事情是一个人可能有一个 Countryid。此人可能与某项工作相关,该工作也可能具有 Countryid。这项工作的雇主有一个国家(等等)——也就是说,我们最终得到了一个非常混乱的图表。
关于问题:我希望能够在 EF / LINQ 查询中访问国家/地区信息,而无需连接。我应该先将多个 FK 添加到数据库中吗?我是否只需在设计器中连接这些关系?当 EF 中有多个表与同一个表相关时,我需要注意什么(如果有的话)?这行得通吗?
基本上只是寻找这样做的最佳实践。
The context of the question is ASP.NET MVC2 / EF4. I have a number of lookup tables in the database which have previously been programmatically referenced, each from a number of other tables... So there might be a country table with country-id shortcode, desc, and half a dozen tables that have a countryid in them. Repeat for 5 or 6 other lookup tables. At the moment there are no FK's - the lookup has been programmatic in the UI of the old database frontend.
The other thing to be wary of is that a person may have an countryid. The person may be related to a job which may also have a countryid. The job has an employer with a countryid (and on and on) - i.e. we end up with a pretty tangled graph.
Onto the question: I would like to be able to reach the country information in EF / LINQ queries without joins. Should I add the multiple FK's to the database first ? Do I just wire these up the relationships in the designer ? What (if anything) do I need to look out for when having multiple tables related to the same table in EF? Will this work at all ?
Just basically looking for best practice in doing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先创建 FK,然后从 EF 设计器中的数据库更新模型。它将自动根据 FK 关系创建实体之间的关联。
它会工作得很好。
需要注意的是,EF 会双向连接您的图表,这可能会导致问题。例如,您创建一些临时 Person 对象并将其上的 Country 设置为现有的 Country 实体。如果该 Country 实体也是在当前上下文中已更改的其他实体的一部分,那么当您保存更改时,您的临时 Person 对象也可能会添加到数据库中! EF 的图表构建有时可能有点过于急切。
Create the FK first, update the model from the database in the EF Designer. It will create the associations between your entities from the FK relationships automatically.
It will work just fine.
The one caveat is that EF will connect up your graph both ways and this can cause issues. For example, you create some temporary Person object and set the Country on it to an existing Country entity. If that Country entity is also part of some other entity that has been changed in the current context then, when you save changes your temporary Person object may be added to the database too! EF's graph building can get a little over-eager sometimes.