简体   繁体   English

为什么我的模型中的两个外键导致外键约束?

[英]Why two foreign keys in my model cause Foreign Key Constraint?

What's the workaround with this? 这有什么解决方法? Can this be achievable using data annotations? 使用数据注释可以实现这一点吗?

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

What's the problem in this model? 这个模型有什么问题? Why do I get this error : 为什么我会收到此错误:

Introducing FOREIGN KEY constraint 'FK_Questiions_AspNetUsers_AskerId' on table 'Questiions' may cause cycles or multiple cascade paths. 在表'Questiions'上引入FOREIGN KEY约束'FK_Questiions_AspNetUsers_AskerId'可能会导致循环或多个级联路径。 Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。 Could not create constraint or index. 无法创建约束或索引。 See previous errors. 查看以前的错误。

You've got your ForeignKey decorations below the properties, when they should be above them. 你的ForeignKey装饰物位于属性下方,当它们位于它们之上时。 The attributes are being applied to the wrong properties. 属性正在应用于错误的属性。

You've also got multiple occurrences of the AskedApplicationUser property. 您还有多次出现AskedApplicationUser属性。

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM