为什么在存在';没有复合键

本文关键字:复合 存在 为什么 | 更新日期: 2023-09-27 18:29:55

我有两个类,每个类都有一个主键(也在DB中验证过——只有一个键,只有一列是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; }
}

当我尝试运行添加迁移时,我会收到以下错误。没有复合主键,也没有多个主键。当我添加Column属性时,它是有效的,但我觉得它不应该是必要的(因此,我怀疑我做错了什么)。

无法确定Beep.Bapp.Thing类型的外键的组合外键顺序。在组合外键属性上使用ForeignKey数据批注时,请确保使用Column数据批注或fluent API指定顺序。


在这个答案中,有一个类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; }
}

为什么在存在';没有复合键

我根本不知道你的代码是如何编译的。试试这个型号:

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;}
}
public class Sup
{
    [Key]
    public int Id { get; set; }
    public int Sub1Id { get; set; }
    public int Sub2Id { get; set; }
    public virtual Sub1 Sub1 { get; set; }
    public virtual Sub2 Sub2 { get; set; }
}