[英]Entity Framework 6 Adding properties to join tables
這是場景:我有一個產品表和一個類別表。 這種關系是多對多的:一個類別可以有一個或多個產品......一個產品可以是一個或多個類別......
Code-First映射看起來像這樣....
public class Product
{
//...additional properties...
public virtual ICollection<Category> AssociatedCategories {get; set;}
}
public class Category
{
//...additional properties...
public virtual ICollection<Product> AssociatedProducts {get; set;}
}
現在,實體框架將創建一個名為ProductCategory的連接表,其中包含ProductID和CategoryID列。 那很棒....
不過,我需要引入一個排序順序...基本上只是一個基數定位索引,但這個數字僅存在於產品和類別相互滿足的關系中。 例如,產品X在類別Y中可能具有排序順序值“5”,但是某些產品 - X - 在類別Z中可能具有不同的排序值(例如10)。
當然,我可以專門為這種類型的東西創建一個實體......但它需要一個新的表...類別ID,產品ID和排序順序將有3列。 我真正希望能夠做的是進入實體框架已經制作的表格......它已經在連接表中跟蹤產品ID和類別ID ....有什么方法可以做使用已經存在的表?
您需要為連接表創建特定實體才能執行此操作。
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; }
}
如果您使用Fluent API配置實體,它將如下所示:
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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.