为什么模型中的两个外键会引起外键约束?

时间:2019-06-24 05:16:48

标签: asp.net entity-framework-core data-annotations ef-core-2.2

此问题的解决方法是什么?使用数据注释可以实现吗?

public class QuestionModel
{
    [Required]
    public int Id { get; set; }

    public long AskedUserId { get; set; }
    [ForeignKey("AskedUserId")]
    public virtual ApplicationUser AskedApplicationUser { get; set; }
    public long AskerId { get; set; }
    [ForeignKey("AskerId")]
    public virtual ApplicationUser AskerApplicationUser { get; set; }
    [Required]
    public string content { get; set; }
    public bool IsAnswered { get; set; }
}

此模型有什么问题?为什么会出现此错误:

  

在表“问题”上引入外键约束“ FK_Questiions_AspNetUsers_AskerId”可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。   无法创建约束或索引。查看以前的错误。

1 个答案:

答案 0 :(得分:0)

ForeignKey装饰应该位于属性上方时,它们已经位于属性下方。该属性被应用于错误的属性。

您还多次出现了AskedApplicationUser属性。

尝试一下:

public class QuestionModel
{
    [Required]
    public int Id { get; set; }

    [ForeignKey("AskedUserId")]
    public long AskedUserId { get; set; }
    [ForeignKey("AskerId")]
    public long AskerId { get; set; }
    public virtual ApplicationUser AskedApplicationUser { get; set; }
    [Required]
    public string content { get; set; }
    public bool IsAnswered { get; set; }
}
相关问题