简体   繁体   中英

Entity Framework messes up my many-to-many self relation

I have a Products Table and a BundleLink Table which defines whicht product is a bundle product of an other.

    public class Product
    {
        public int Id { get; set; }

        public ICollection<BundleLink> MasterOf { get; set; }

        public ICollection<BundleLink> BundleOf { get; set; }
    }

    public class BundleLink
    {
        public int Id { get; set; }

        public Product Master { get; set; }

        public Product Bundle { get; set; }

        public int Quantity { get; set; }
    }

So when I go to a master product, I see what bundles are referring to it and in the other direction.

But entity framework creates 4 columns in the sql server in the BundleLink table. It creates one for the product fields i defined and two more foreign keys where one of them is null everytime, it depends on in which direction i add a bundle. How can i define for EF which BundeLink collection belongs to which Product?

I hope my description is understandable. Thanks in advance.

In Entity Framework you need to follow Data Annotations - ForeignKey Attribute in EF 6 & EF Core.

The ForeignKey attribute is used to configure a foreign key in the relationship between two entities in EF 6 and EF Core. It overrides the default conventions. As per the default convention, EF makes a property as foreign key property when its name matches with the primary key property of a related entity.

More information: http://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx

Thanks, raghu

How can i define for EF which BundeLink collection belongs to which Product?

You have two solutions:

  • in OnModelCreating method of your DbConext use fluent configuration so by defining relation it helps EF to know which collections belong to which.
  • decorate your collection with InverseProperty attribute. So in your collections you will have InversProperty("Master") for MasterOf collection and InversProperty("Bundle") for BundleOf .

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