【问题标题】:DELETE conflicts with the REFERENCE constraint while using nullable foreign key使用可为空的外键时,DELETE 与 REFERENCE 约束冲突
【发布时间】:2017-09-16 15:18:54
【问题描述】:

我正在使用 ASP.Net MVC。我有两个类是一对多和多对多相关的。

public class Image
{
    public Image() { }

    public long Id { get; set; }

    // other properties are removed for clarity

    public virtual IList<Branch> Branches { get; set; }
}


public class Branch
{
    public Branch() { }

    public long Id { get; set; }

    // other properties are removed for clarity

    public long? ImageId { get; set; }
    public virtual Image Image { get; set; }

    public virtual IList<Image> Images { get; set; }
}

分支可以有多个图像 (Branch.Images)。但我想单独存储他们的主图像(Branch.Image)。我认为这可能有助于提高速度。由于分支可能没有图像,因此该属性被定义为 nullable。正如引用所述,这种定义应该在 Branches 表中定义一个外键,它确实如此。但问题是当一个作为分支主图像的图像被删除时。它会导致此错误:

DELETE 语句与 REFERENCE 约束冲突 “FK_Branches_Images_ImageId”。冲突发生在 数据库“数据库”,表“分支”,列“ImageId”。这 语句已终止。

但它应该将外键设置为空,因为该分支没有主图像。

我也应该使用 Fluent API 还是模型定义有问题?

【问题讨论】:

  • 用 SQL 的说法,你想要的是ON DELETE SET NULL。搜索这些词和entity framework 会发现许多现有帖子。
  • 你是如何定义级联动作的?
  • @Rob 我没有。据说这个模型定义就足够了。
  • 谢谢@Damien_The_Unbeliever。我在这里找到了解决方案:stackoverflow.com/a/15230641/1650088

标签: c# entity-framework code-first


【解决方案1】:

仅当子实体也加载到上下文中时,自动设置为 null 才有效,而不仅仅是父实体。在删除它之前,您需要将子代包含到您的父代中。

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2011-04-16
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多