2013-03-16 26 views
33

這些是我簡化的域類。Fluent Api實體框架多列作爲主鍵

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

這是我的映射類。但它不起作用。

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

我應該如何映射這些類來提供,這樣一個產品可以在多個類別中可以看出?

回答

76

使用匿名類型的對象,而不是2分隔的語句:

HasKey(pc => new { pc.ProductId, pc.CategoryId}); 

從MSDN:EntityTypeConfiguration.HasKey Method

如果主鍵由多個特性然後指定匿名類型包括屬性。例如,在C#t => new { t.Id1, t.Id2 }和Visual Basic .Net Function(t) New From { t.Id1, t.Id2 }中。