【发布时间】:2016-04-16 05:00:54
【问题描述】:
我有两个类,每个类都有一个主键(也在数据库中验证 - 只有一个键,只有一列是 PK)。
public class Sub1
{
[Key]public int Id {get; set;}
[Required]public int Value {get; set;}
}
public class Sub2
{
[Key]public int Id {get; set;}
[Required]public int Value {get; set;}
}
然后我添加了第三个类,它使用上面两个中的 Id 列作为外键。
public class Sup
{
[Key]public int Id { get; set; }
[ForeignKey(Sub1)]public int Sub1Id { get; set; }
[ForeignKey(Sub2)]public int Sub2Id { get; set; }
public virtual Sub1 { get; set; }
public virtual Sub2 { get; set; }
}
当我尝试运行 Add-Migration 时,我收到以下错误。没有复合主键,我在任何地方都没有多个主键。当我添加 Column 属性时,它可以工作,但我觉得它不应该是必要的(因此,我怀疑我做错了什么)。
无法确定 Beep.Bapp.Thing 类型外键的复合外键排序。在复合外键属性上使用 ForeignKey 数据注释时,请确保使用 Column 数据注释或 fluent API 指定顺序。
在this answer 中,有类Category 和这里 我知道我们需要添加列排序信息。
public class Category
{
[Key, Column(Order = 0)]
public int CategoryId2 { get; set; }
[Key, Column(Order = 1)]
public int CategoryId3 { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
[Key]
public int ProductId { get; set; }
public string Name { get; set; }
[ForeignKey("Category"), Column(Order = 0)]
public int CategoryId2 { get; set; }
[ForeignKey("Category"), Column(Order = 1)]
public int CategoryId3 { get; set; }
public virtual Category Category { get; set; }
}
【问题讨论】:
标签: c# ef-code-first foreign-keys multiple-columns composite-key