1

I want to build a database with Entity Framework Core. I use the command prompt and migrations to create the database. But as you can see on my diagram, I have a many-to-many relationship. How do I create this relationship with my classes below?

enter image description here

Code:

public class ShoppingDbContext : IdentityDbContext<User>
{
    public ShoppingDbContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder     optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }

    public DbSet<Order> Orders { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<PartCategory> PartCategory { get; set; }
    public DbSet<Part> Parts { get; set; }
}

public class Product 
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public double Price { get; set; }

    public List<PartCategory> PartCategory { get; set; } 
}

public class PartCategory
{
    public int PartCategoryId { get; set; }
    public string Category { get; set; }

    public List<Part> Parts { get; set; }
}

//update

public class ProductPartCategory
{
public int ProductId { get; set; }
public Product Product { get; set; }

public int PartCategoryId { get; set; }
public PartCategory PartCategory { get; set; }
}

public class Product 
{

public int ProductId { get; set; }
public string ProductName { get; set; }
public double Price { get; set; }
public List<PartCategory> PartCategories{ get; set; } 

}

 public class PartCategory
{
public int PartCategoryId { get; set; }
public string Category { get; set; }
public List<Product> Products { get; set; }

//dont mind this propertie its for other stuff
public List<Part> Parts { get; set; }
}
Robel Haile
  • 309
  • 1
  • 5
  • 18
  • You should read the documentation: https://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many – Mike Brind Sep 22 '16 at 15:11
  • Possible duplicate of [How to create a many to many relationship with latest nightly builds of EF7?](http://stackoverflow.com/questions/29442493/how-to-create-a-many-to-many-relationship-with-latest-nightly-builds-of-ef7) – tmg Sep 22 '16 at 16:50

2 Answers2

1

You can try as shown below using Fluent API.

Note :

Many-to-many relationships without an entity class to represent the join table are not yet supported. However, you can represent a many-to-many relationship by including an entity class for the join table and mapping two separate one-to-many relationships.

public class ShoppingDbContext: DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<PartCategory> PartCategories{ get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ProductPartCategory>()
                .HasKey(t => new { t.ProductId, t.PartCategoryId });

            modelBuilder.Entity<ProductPartCategory>()
                .HasOne(pt => pt.Product)
                .WithMany(p => p.ProductPartCategories)
                .HasForeignKey(pt => pt.ProductId);

            modelBuilder.Entity<ProductPartCategory>()
                .HasOne(pt => pt.PartCategory)
                .WithMany(t => t.ProductPartCategories)
                .HasForeignKey(pt => pt.PartCategoryId);
        }
    }

Your models should be like this :

 public class Product 
  {

    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public double Price { get; set; }
    public List<ProductPartCategory> ProductPartCategories { get; set; } 

  }

 public class PartCategory
   {
     public int PartCategoryId { get; set; }
     public string Category { get; set; }
     public List<ProductPartCategory> ProductPartCategories { get; set; } 
   }

  public class ProductPartCategory
    {
      public int ProductId { get; set; }
      public Product Product { get; set; }

      public int PartCategoryId { get; set; }
      public PartCategory PartCategory { get; set; }
   }
Sampath
  • 63,341
  • 64
  • 307
  • 441
  • i used your code. But get this error message when i start the web app .... you can se in the link (https://gyazo.com/cb7df90ddc75c31db451a5cb17e2acf0) – Robel Haile Sep 22 '16 at 19:36
  • your code is not my one.try my code.as shown above. `modelBuilder.Entity() .HasOne(pt => pt.Product) .WithMany(p => p.PartCategories) .HasForeignKey(pt => pt.ProductId);` – Sampath Sep 23 '16 at 01:35
  • use exact code which I have given.including model classes.you have to change your ones as like my code. – Sampath Sep 23 '16 at 01:36
  • all i did was add a casrting. If i dont do that i use your code exactly i get this error message (https://gyazo.com/14b063e96c8f2bca52af21535d03729b) – Robel Haile Sep 23 '16 at 05:44
  • can you show your changed models code also ? put that on your original post under new section named as **Update**. – Sampath Sep 23 '16 at 06:42
  • can you remove `//dont mind this propertie its for other stuff public List Parts { get; set; }` on your update and test it again. – Sampath Sep 23 '16 at 08:41
  • please see this : https://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many – Sampath Sep 23 '16 at 15:00
  • sorry,I have done it wrongly. please see the latest update and let me know about the result now. – Sampath Sep 24 '16 at 05:16
  • Great.You can `Up-Vote` too.It'll give more pleasure to me :D Here you can see how to do that : http://stackoverflow.com/tour – Sampath Sep 27 '16 at 08:43
0

You've already gotten some answers, but here is how you can find out for yourself...

The way I answer all of my EF modeling questions is to have dotnet reverse engineer the data structure for me. By executing a scaffolding command in a command line prompt (from inside of your project files directory), dotnet will create a bunch of files that you can then either use directly or examine for structure and delete to your liking.

The only way this will work is if you have all of your relationships (foreign keys, etc) set up properly in your development DB.

dotnet ef dbcontext scaffold "YourConnectionString" Microsoft.EntityFrameworkCore.SqlServer -a -t PartCategory -t Products -t ProducsPartCategory --o OutputDirectory
Simon Ordo
  • 1,517
  • 2
  • 14
  • 23