I have a many to many relation, and I want to add an intermediate class, which would enable me adding the many to many relations using repository pattern.
What I can't figure out is the mapping.
Here's the structure
public class Product
{
public Product()
{
Categories = new HashSet<Category>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Category> Categories { get; set; }
}
public class Category
{
public int Id { get; set; }
public String Name { get; set; }
public ICollection<Product> Products { get; set; }
}
public class PCMap
{
public int product_id { get; set; }
public int category_id { get; set; }
public Product Product { get; set; }
public Category Category { get; set; }
}
And the Mapping
modelBuilder.Entity<Product>()
.HasEntitySetName("PCMap")
.HasMany(p=>p.Categories)
.WithMany(p=>p.Products)
.Map(m=>
{
m.MapLeftKey("product_id");
m.MapRightKey("category_id");
m.ToTable("PCMap");
});
modelBuilder.Entity<PCMap>()
.ToTable("PCMap");
modelBuilder.Entity<PCMap>().HasKey(k => new
{
k.category_id,
k.product_id
});
modelBuilder.Entity<PCMap>()
.HasRequired(p=>p.Product)
.WithMany()
.HasForeignKey(p => p.product_id);
modelBuilder.Entity<PCMap>()
.HasRequired(p => p.Category)
.WithMany()
.HasForeignKey(p => p.category_id);
Here's the error that I get.. How do I fix this ?