简体   繁体   中英

Entity Framework - many to many

I have a Packages table containing info about a package (carrier, weight..).

I want to associate Products for that package so I did the following:

public class Package
{
    public int ID { get; set; }
    public Order Order { get; set; }
    public int Weight { get; set; }
    public List<Product> Products { get; set; }
}

What happened is that it added package_id to the products table, but this is a many to many relationship. How can I maintain, if possible, the products list in the packages table but have it know that it is a many to many?

Thanks.

If you want to Package to have many to many relationship with product, add this instead of List

public virtual ICollection<Products> Products {get;set;}

And in Product table add this line

public virtual ICollection<Package> Packages {get;set;}

EF will create a new table named as ProductsPackages. Each row represens one relation ship which each other.

Many to many relationship in entity framework are created with junction tables. You can create them with by mapping the relationship, or you can create the junction table yourself.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

modelBuilder.Entity<Package>()
            .HasMany<Product>(s => s.Products)
            .WithMany(c => c.Packages)
            .Map(cs =>
                    {
                        cs.MapLeftKey("PackageRefId");
                        cs.MapRightKey("ProductRefId");
                        cs.ToTable("PackageProduct");
                    });

}

create table yourself:

 public class PackageProduct
 {
    public virtual Package Package { get; set; }
     public virtual Product Product { get; set; }
 }

Jimmy Bogard discusses which method to use: https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/

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