locked
Independent Many-to-Many? RRS feed

Answers

  • Yes, you can create a many to many association as long as you provide a navigation property on at least on of the association's ends like the following example:

    public class Product
    {
      public int ProductId { get; set; }
      public virtual ICollection<Category> Categories { get; set; }
    }
    
    public class Category
    {
      public int CategoryId { get; set; }    
    }
    
    public class Context : DbContext
    {
      public DbSet<Product> Products { get; set; }
      public DbSet<Category> Categories { get; set; }
    
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
        modelBuilder.Entity<Product>()
              .HasMany(p => p.Categories)
              .WithMany();
      }
    

     

    • Proposed as answer by Morteza Manavi Friday, March 11, 2011 10:29 PM
    • Marked as answer by Mike-E_wins Friday, March 11, 2011 10:29 PM
    Friday, March 11, 2011 10:29 PM

All replies

  • Yes, you can create a many to many association as long as you provide a navigation property on at least on of the association's ends like the following example:

    public class Product
    {
      public int ProductId { get; set; }
      public virtual ICollection<Category> Categories { get; set; }
    }
    
    public class Category
    {
      public int CategoryId { get; set; }    
    }
    
    public class Context : DbContext
    {
      public DbSet<Product> Products { get; set; }
      public DbSet<Category> Categories { get; set; }
    
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
        modelBuilder.Entity<Product>()
              .HasMany(p => p.Categories)
              .WithMany();
      }
    

     

    • Proposed as answer by Morteza Manavi Friday, March 11, 2011 10:29 PM
    • Marked as answer by Mike-E_wins Friday, March 11, 2011 10:29 PM
    Friday, March 11, 2011 10:29 PM
  • BEAUTIFUL!  THANK YOU!
    Friday, March 11, 2011 10:30 PM