您只需通过导航属性设置产品和类别实体之间的关系。 EF会根据自己的多对多关系建立正确的表结构。所以不需要自己的关系实体。
请查看:many-to-many-relationship in EF
例如:
产品类别:
public class Product
{
// other properties
public virtual ICollection<Category> Categories { get; set; }
}
类别类:
public class Category
{
// other properties
public virtual ICollection<Product> Products { get; set; }
}
还是我误解了你的问题?
编辑:
如果您需要像 ProductConfig 这样的单独实体,则应尝试通过以下方式将其设置为唯一索引约束:
modelBuilder
.Entity<ProductConfig>()
.HasIndex(pc => new {pc.Category, pc.Product})
.IsUnique();
如需更多信息,请阅读:HasIndex - Fluent API
EDIT 2(获取信息后解决方案是 EF ):
在您最后一次问题编辑之后,需要另一种解决方法。
来了……
您需要如下结构:
产品
public class Product
{
// other properties
public virtual ICollection<ProductConfig> ProductConfigs { get; set; }
}
类别
public class Category
{
// other properties
public virtual ICollection<ProductConfig> ProductConfigs { get; set; }
}
产品配置
public class ProductConfig
{
// other properties
public virtual Category { get; set; }
public virtual Product { get; set; }
public virtual ProductCategoryType { get; set; }
}
要在 EF
modelBuilder.Entity<ProductConfig>()
.Property(e => e.Category)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("YourIndex", 1) { IsUnique = true }));
modelBuilder.Entity<ProductConfig>()
.Property(e => e.Product)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("YourIndex", 2) { IsUnique = true }));
modelBuilder.Entity<ProductConfig>()
.Property(e => e.ProductCategoryType)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute("YourIndex", 3) { IsUnique = true }));
在 EF 6.2 中:
modelBuilder.Entity<Person>()
.HasIndex(p => new { p.Category, p.Product, p.ProductCategoryType })
.IsUnique();
编辑 3
如果您的 ProductConfig 类中没有主键,或者您在我没有添加的示例中使用了我的主键,因为我认为您已经拥有该类。
可以将多个属性设置为键。这也会产生独特的组合。
您将使用以下内容存档 - 而不是索引内容:
modelBuilder.Entity<ProductConfig>()
.HasKey(pc => new { pc.Category, pc.Product, pc.ProductCategoryType });
如需更多信息,请查看MS docs。
您也可以添加一个 Id 作为主键,而不是需要索引。