c# - 使用可为空的外键时,DELETE 与 REFERENCE 约束冲突

标签 c# entity-framework code-first

我正在使用 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)。我认为这可能有助于提高速度。由于分支可能没有图像,因此此属性定义为可为空。正如引用资料所述,这种定义应该在 Branches 表中定义一个外键,它确实如此。但问题是当作为分支主图像的图像被删除时。它会导致此错误:

The DELETE statement conflicted with the REFERENCE constraint "FK_Branches_Images_ImageId". The conflict occurred in database "Database", table "Branches", column 'ImageId'. The statement has been terminated.

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

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

最佳答案

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

关于c# - 使用可为空的外键时,DELETE 与 REFERENCE 约束冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43511907/

相关文章:

c# - 限制在 C# 中使用泛型创建子表单

entity-framework - 如何在 Visual Studio 2015 中使用 Entity Framework 电动工具?

entity-framework - Subsonic 3 VS Entity Framework

c# - 使用 Entity Framework Core 2 Code First 创建 varchar

c# - 没有子导航属性的 EF 一对多外键

asp.net - Entity Framework CTP5,代码优先。可选导航属性

c# - 我应该在哪里放置接口(interface)和实现

c# - 代码优先,当我启用迁移时,我得到 “No context type was found in the assembly ' DOC'”

c# - 在 Datalist 中显示 Mysql 数据库中的图像

asp.net - 是否可以在共享主机上使用 EF CodeFirst?特别是初始化程序?