实体框架多柱由流畅API主键 [英] Entity Framework Multiple Column as Primary Key by Fluent Api

查看:108
本文介绍了实体框架多柱由流畅API主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以上是我简单的领域类。

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 ?

推荐答案

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

Use anonymous type object instead of 2 separated statements:

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

从MSDN:<一href="http://msdn.microsoft.com/en-us/library/gg671266%28v=vs.103%29.aspx">EntityTypeConfiguration.HasKey方法

如果主键是由多个性能高达然后指定一个匿名类型包括属性。例如,在C# T =&GT;新{t.Id1,t.Id2} 并在Visual Basic .NET 函数(t)的新从{t.Id1,t.Id2}

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

这篇关于实体框架多柱由流畅API主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆