实体框架 4 - 关联
EF 4 不支持不基于外键/主键的关联。在很多情况下,您需要使用非键字段在表之间导航。
例如,药物表具有:
medID (PK)
medGrouperID
medName
成分表具有:
ingredientID (PK)
ingredientName
链接表具有:
medGrouperIDID (PK)
ingredientID (PK)
在这种情况下,EF 不允许我在药物和链接表之间创建关联,因为两者都没有对方的外键。
我已经很长时间没有做过任何数据库设计了,所以我很难理解这个限制;这是良好的数据库设计还是 EF 的失败?
编辑
MedGrouperID 允许将具有相同成分、用途、说明等的所有药物分组在一起。如果每种药物都有自己的成分、用途等记录集,这将消除可能存在的重复数据。
添加新的 MedGrouper 表会起作用,但这将需要额外的联接,这对性能不利。
药物治疗
* MedID (PK)
* MedGrouperID (FK)
* MedName
MedGrouper * 医疗ID (FK) * MedGrouperID (PK)
成分
* IngredientID (PK)
* IngrediantName
药物成分(连接/连接表)
* MedGrouperID (PK, FK)
* IngredientID (PK, FK)
/编辑
EF 4 does not support associations that are not based on foreign/primary keys. There are lots of occasions where you need to navigate between tables using non-key fields.
For example, a medications table has:
medID (PK)
medGrouperID
medName
an ingredients table has:
ingredientID (PK)
ingredientName
and a link table has:
medGrouperIDID (PK)
ingredientID (PK)
In this case EF doesn't let me create an association between medications and the link table as neither has a foreign key for the other.
I haven't done any db design for a long time so i'm struggling to understand this restriction; Is this following good database design or a failure of EF?
EDIT
The MedGrouperID allows all medications with the same ingredients, uses, instructions etc to be grouped together. This removes the duplication of data that would exist if every medicine had its own set of records for ingredients, uses etc.
Adding a new MedGrouper table will work but this would neccessitate an additional join which can't be good for performance.
Medication
* MedID (PK)
* MedGrouperID (FK)
* MedName
MedGrouper
* MedID (FK)
* MedGrouperID (PK)
Ingredient
* IngredientID (PK)
* IngrediantName
MedicationIngredients (junction/join table)
* MedGrouperID (PK, FK)
* IngredientID (PK, FK)
/EDIT
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是 EF 的失败,而是不正确的数据库设计(抱歉直率了)。从纯数据库查询的角度来看,该设计不起作用,因此您也不能指望 EF 能够解决这个问题。
您似乎在药物和成分之间有一个
*..*
。因此,您应该有以下表格:
药物
成分
药物成分 (连接/连接表)
如果您生成从使用实体框架的模型来看,EF 将创建具有多对多关联的两个实体,并且根本不需要映射联接表。
您必须记住的是,关系是基于引用完整性的,而您在当前的数据库模式中没有正确设置引用完整性。
HTH。
It's not a failure of EF, it's an incorrect database design (sorry for the bluntless). That design would not work from a pure database query perspective, therefore you cannot expect EF to work it out either.
It appears you have a
*..*
between Medications and Ingredients.Therefore you should have the following tables:
Medication
Ingredient
MedicationIngredients (junction/join table)
If you generate a model from that using Entity Framework, EF will create the two entities with the many to many association present, and the join table will not have to be mapped at all.
The thing you have to remember is relationships are based on referential integrity, which you did not have correctly setup in your current database schema.
HTH.