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; }
}
2

2 Answers 2

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; }
   }
Sign up to request clarification or add additional context in comments.

9 Comments

i used your code. But get this error message when i start the web app .... you can se in the link (gyazo.com/cb7df90ddc75c31db451a5cb17e2acf0)
your code is not my one.try my code.as shown above. modelBuilder.Entity<ProductPartCategory>() .HasOne(pt => pt.Product) .WithMany(p => p.PartCategories) .HasForeignKey(pt => pt.ProductId);
use exact code which I have given.including model classes.you have to change your ones as like my code.
all i did was add a casrting. If i dont do that i use your code exactly i get this error message (gyazo.com/14b063e96c8f2bca52af21535d03729b)
can you show your changed models code also ? put that on your original post under new section named as Update.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.