[英]Multiple foreign keys pointing to same table in Entity Framework are indistinguisible
I'm unable to distinguish between foreign keys when two or more point to the same table through the database context. 当两个或多个通过数据库上下文指向同一张表时,我无法区分外键。
For example, if I have a db with two tables, Users and Invoices. 例如,如果我有一个包含两个表的数据库,即用户表和发票。
Users has two fields: userId and userName
Invoices has three fields: invoiceNumber, cashierUserId, supervisorUserId
cashierUserId and supervisorUserId are foreign keys pointing to userId in the Users table. cashierUserId和supervisorUserId是指向Users表中的userId的外键。
Now in entity framework via the db context when I try to get the cashier or supervisor's user name I can't tell which user name I'm going to get. 现在,在通过db上下文的实体框架中,当我尝试获取收银员或主管的用户名时,我无法确定要获取哪个用户名。
dbContext.Invoices.Single(i => i.invoiceNumber == 1).Users.userName;
Which user name do I get? 我得到哪个用户名? The cashier's or the supervisor's?
收银员还是主管? How do I tell it which one I want?
如何告诉我要哪一个?
First off, your code has an issue. 首先,您的代码有问题。 The "Users" collection wouldn't have a property called "userName".
“用户”集合将没有名为“ userName”的属性。 It should probably read:
它可能应该显示为:
dbContext.Invoices.Single(i => i.invoiceNumber == 1).Users.First().userName;
Obviously, .First() is not going to help with the "distinguishing" problem. 显然,.First()不能解决“区别”问题。 For that, I see two solutions:
为此,我看到了两种解决方案:
Modify your context so each navigation property has a special name ("Cashier", "Supervisor"). 修改您的上下文,以便每个导航属性都有一个特殊名称(“收银员”,“主管”)。 Then you would just write:
然后,您只需编写:
dbContext.Invoices.Single(i => i.invoiceNumber == 1).Cashier.userName;
Give your user a "type" field. 给您的用户一个“类型”字段。 This could be a string stored in the user table, or likely a foreign key into a "UserTypes" table (in a normalized database).
这可以是存储在用户表中的字符串,也可以是“ UserTypes”表中的外键(在规范化数据库中)。 Then your query becomes:
然后您的查询变为:
dbContext.Invoices.Single(i => i.invoiceNumber == 1).Users.First(u => u.UserType == "Cashier").userName;
Using a different table would change the predicate a bit, but you get the idea. 使用不同的表会稍微改变谓词,但是您可以理解。 To help guide your design, remember that EF isn't very different than standard SQL.
为了帮助指导设计,请记住EF与标准SQL并没有太大不同。 How would you craft a standard SQL query to distinguish the two?
您将如何制定标准的SQL查询来区分两者? You would base it on foreign key (the first option), or another field on the users table (the second option).
您将基于外键(第一个选项)或用户表上的另一个字段(第二个选项)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.