Fluent Api将实体框架多列作为主键

Bar*_*ğlu 46 .net c# entity-framework entity-framework-5

这些是我的简化域类.

public class ProductCategory
{
    public int ProductId { get; set; }
    public int CategoryId { get; set; }

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

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
} 

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentCategoryId { get; set;} 
} 
Run Code Online (Sandbox Code Playgroud)

这是我的映射类.但它不起作用.

public class ProductCategoryMap : EntityTypeConfiguration<ProductCategory>
{
    public ProductCategoryMap()
    {
        ToTable("ProductCategory");
        HasKey(pc => pc.ProductId);
        HasKey(pc => pc.CategoryId);
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该如何映射这些类来提供,以便可以在多个类别中看到一个产品?

Mar*_*zek 98

使用匿名类型对象而不是2个单独的语句:

    HasKey(pc => new { pc.ProductId, pc.CategoryId});
Run Code Online (Sandbox Code Playgroud)

从MSDN:EntityTypeConfiguration.HasKey方法

如果主键由多个属性组成,则指定包含属性的匿名类型.例如,在C#t => new { t.Id1, t.Id2 }和Visual Basic .Net中Function(t) New From { t.Id1, t.Id2 }.