Entity Framework 6 Adding properties to join tables

c# e-commerce entity-framework entity-framework-6

Question

I have a table with products and another table with categories. The link is many-to-many: a product may belong to one or more categories, and a category may have one or more products.

This is how the Code-First mapping appears.

public class Product
{
  //...additional properties...
  public virtual ICollection<Category> AssociatedCategories {get; set;}
}

public class Category
{
  //...additional properties...
  public virtual ICollection<Product> AssociatedProducts {get; set;}
}

Entity framework will now generate a join table with the columns ProductID and CategoryID called ProductCategory from scratch. That's fantastic.

The problem is that I need to provide a sort order—basically, just a cardinal positioning index—but this number only appears at the intersection of the relationships between the categories of products. For instance, a product X might be sorted with a value of "5" in Category Y, while in Category Z, that same product X might be sorted with a different value, such as "10."

Naturally, I could design a specific entity for this kind of situation, but that would call for the creation of a new table with three columns for the Category ID, Product ID, and sort order. I'd really like to be able to use the table that entity framework already created; it will already keep track of the product and category IDs in the join table. Is there any way to use the table that currently exists?

1
0
4/2/2014 6:24:19 PM

Accepted Answer

To accomplish this, a special entity must be made for the join table.

public class Product
{
  //...additional properties...
  public virtual ICollection<ProductCategoryXref> AssociatedCategories {get; set;}
}

public class Category
{
  //...additional properties...
  public virtual ICollection<ProductCategoryXref> AssociatedProducts {get; set;}
}

public class ProductCategoryXref
{
    public int ProductId { get; set; }
    public int CategoryId { get; set; }
    public int SortOrder { get; set; }
    // Additional Columns...

    public virtual Product Product { get; set; }
    public virtual Category Category { get; set; }
}

If you are configuring your entities using the Fluent API, it will resemble this:

 public class ProductCategoryXrefMap : EntityTypeConfiguration<ProductCategoryXref>
 {
      ProductCategoryXrefMap()
      {
           HasKey(pk => new { pk.ProductId, pk.CategoryId });
           HasRequired(p => p.Product).WithMany(p => p.AssociatedCategories).HasForeignKey(fk => fk.ProductId);
           HasRequired(p => p.Category).WithMany(p => p.AssociatedProducts).HasForeignKey(fk => fk.CategoryId);
           ToTable("ProductCategoryXref");
      }
 }
2
4/2/2014 7:18:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow