简体   繁体   中英

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!

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:

I'm not sure of the answer to your question but I would make 1 recommendation, get rid of the PackageVariant table. 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. This will enforce your rule of 1 package exactly per variant. But none to multiple variants per package.

Thanks Lee

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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