Entity Framework 6 Adding properties to join table

2019-09-03 21:42发布

This is the scenario: I have a products table and a categories table. The relationship is many-to-many: a category can have 1 or more products....and a product can be in 1 or more categories...

The Code-First mapping looks like this....

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

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

Now, under the hood, entity framework will create a join table called ProductCategory with columns ProductID and CategoryID. That's great....

Here's the thing though, I need to introduce a sort order...basically just a cardinal positioning index, but this number exists only at the part in the relationship where product and category meet each other. For example, a product X might have a sort order value of "5" in Category Y, but that some product--X--could have a different sort value--say 10--in Category Z.

Naturally, I could create an entity specifically for this type of thing...but it would require a new table be made...there would be 3 columns for the Category ID, Product ID, and sort order. What I'd really like to be able to do is tap into the table that entity framework already made....it will already keep track of products IDs and category IDs in the join table....is there any way to make use of the table that already exists?

1条回答
劫难
2楼-- · 2019-09-03 22:32

You need to create a specific entity for the join table in order to do this.

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 using the Fluent API to configure your entities it will look something like 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");
      }
 }
查看更多
登录 后发表回答