简体   繁体   English

使用实体框架的复杂关系映射

[英]Complex Relationship Mapping using Entity Framework

I have this database 我有这个数据库

Packages (packageID, package_name , .... )
PackageVariant (packageID, variantID)
Variant (variantID, variant_name, .... )
VariantProduct (variantID, productID, quantity)
Product (productID, product_name, .... )

I have modelled it in Entity Framework, I don't know the multiplicities but they should be based on below: 我已经在实体框架中对其建模,我不知道多重性,但是它们应该基于以下内容:

A Package can have None or Multiple Variants 套件可以没有或具有多个变体
A Variant can be associated with only One Package (can't be none or multiple) 变体只能与一个包关联(不能是一个或多个)
One Variant can have One or Multiple Products 一个变体可以具有一个或多个产品
Products are associated with None or Multiple Variants 产品与无或多个变体相关

When a Package is deleted, all Variants of that Package must be deleted. 删除软件包时,必须删除该软件包的所有变体。
When a Variant is deleted nothing else is needed to be deleted. 删除变体后,无需删除其他任何内容。
When a Product is deleted, all associations with Variants need to be deleted. 删除产品后,所有与变体的关联都需要删除。

If you can provide help with the multiplicities and where the OnDelete:Cascade needs to be set that would be great! 如果您可以提供有关多重性的帮助以及需要在哪里设置OnDelete:Cascade的地方,那就太好了!

I also need to be able to do this: 我还需要能够做到这一点:

var ptx = new MyEntities();
Variant newVariant = new Variant()
{
    setRelevantProperty = value
};
Product selectedProduct = ptx.Products.First(o => o.productID == productID);
newVariant.Products.Add(selectedProduct);
Package packageToAddVariantTo = ptx.Packages.First(o => o.packageID == packageID);
packageToAddVariantTo.Variants.Add(newVariant);
ptx.SaveChanges();

without getting an error due to "There is no Insert, Update set" or anything else that relies on the mappings. 不会由于“没有插入,更新集”或任何其他依赖于映射的错误而出错。 So how to correctly map this complex database would be good :) 因此,如何正确映射此复杂数据库将是一个好方法:)

I have read a few posts, books and I can't seem to find the answer. 我已经阅读了一些帖子,书籍,但似乎找不到答案。

Thanks 谢谢

Lee O got the answer, I'll just re post it as an answer rather than a comment for reader clarity: Lee O得到了答案,为了方便读者阅读,我将其重新发布为答案,而不是发表评论:

I'm not sure of the answer to your question but I would make 1 recommendation, get rid of the PackageVariant table. 我不确定您的问题的答案,但我会提出1条建议,摆脱PackageVariant表。 You only need a table like that when you have a multiple to multiple relationship. 当您具有多对多关系时,只需要一个这样的表。 Just add a column in the variant table called packageId and make it a foreign key to the package table and not null. 只需在变量表中添加一列称为packageId并将其作为包表的外键即可,而不是null。 This will enforce your rule of 1 package exactly per variant. 这将严格执行每个变体1个软件包的规则。 But none to multiple variants per package. 但是每个软件包都没有多个变体。

Thanks Lee 谢谢李

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM