Database Reference
In-Depth Information
Listing 6-4.
Creating the Product POCO Entity Class
[Table("Product", Schema = "Chapter6")]
public class Product
{
public Product()
{
RelatedProducts = new HashSet<Product>();
OtherRelatedProducts = new HashSet<Product>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
// Products related to this product
public virtual ICollection<Product> RelatedProducts { get; set; }
// Products to which this product is related
public virtual ICollection<Product> OtherRelatedProducts { get; set; }
}
Add an auto-property of type
DbSet<Product>
to your DbContext subclass.
3.
Override the
OnModelCreating
method of DbContext in your subclass to create the
many-to-many self-referencing relationship mapping, as shown in Listing 6-5.
4.
Listing 6-5.
Overriding OnModelCreating in the DbContext Subclass to Create the
Many-to-Many Self-Referencing Mapping
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Product>()
.HasMany(p => p.RelatedProducts)
.WithMany(p => p.OtherRelatedProducts)
.Map(m =>
{
m.MapLeftKey("ProductId");
m.MapRightKey("RelatedProductId");
m.ToTable("RelatedProduct", "Chapter6");
});
}
How It Works
As you can see, the Entity Framework supports a many-to-many self-referencing association with little effort. We
created two navigation properties in our Product class, RelatedProducts and OtherRelatedProducts, and mapped
those properties to the underlying database schema in our DbContext subclass.