C# 实体框架多列作为 Fluent Api 的主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15454696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework Multiple Column as Primary Key by Fluent Api
提问by Bar?? Velio?lu
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 ?
我应该如何映射这些类来提供,以便可以在多个类别中看到一个产品?
采纳答案by MarcinJuraszek
Use anonymous type object instead of 2 separated statements:
使用匿名类型对象而不是 2 个分隔的语句:
HasKey(pc => new { pc.ProductId, pc.CategoryId});
From MSDN: EntityTypeConfiguration.HasKey Method
来自 MSDN:EntityTypeConfiguration.HasKey 方法
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 .NetFunction(t) New With { t.Id1, t.Id2 }
.
如果主键由多个属性组成,则指定包含这些属性的匿名类型。例如,在 C#
t => new { t.Id1, t.Id2 }
和 Visual Basic .Net 中Function(t) New With { t.Id1, t.Id2 }
。
回答by saminpa
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'.
令人沮丧的是,特别是如果您碰巧不精通 lambda,则 MSDN VB 示例是错误的……应该是“With”,而不是“From”。
(Thanks Aki Siponen)
(感谢Aki Siponen)