简体   繁体   中英

Entity Framework 6 Adding properties to join tables

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?

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");
      }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM