我正在使用 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/