Entity Framework Multiple Column as Primary Key by Fluent Api

僤鯓⒐⒋嵵緔 提交于 2019-11-28 02:23:36

问题


These are my simplified domain classes.

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

This is my mapping class. But it doesnt work.

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

How should I map these classes to provide, so that one product can be seen in multiple categories ?


回答1:


Use anonymous type object instead of 2 separated statements:

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

From MSDN: EntityTypeConfiguration.HasKey Method

If the primary key is made up of multiple properties then specify an anonymous type including the properties. For example, in C# t => new { t.Id1, t.Id2 } and in Visual Basic .Net Function(t) New From { t.Id1, t.Id2 }.




回答2:


Frustratingly, particularly if you happen not to be fluent in lambda, the MSDN VB example is wrong... that should be a 'With', not a 'From'.

(Thanks Aki Siponen)



来源:https://stackoverflow.com/questions/15454696/entity-framework-multiple-column-as-primary-key-by-fluent-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!