jjzjj

c# - EF4.1 代码优先 : How to disable delete cascade for a relationship without navigation property in dependent entity

coder 2024-05-20 原文

假设我有这两个非常基本的实体:

public class ParentEntity
{
   public int Id;
   public virtual ICollection<ChildEntity> Childrens;
}

public class ChildEntity
{
   public int Id;
   public int ParentEntityId; // Foreign Key
   public virtual ParentEntity parent; // [NOTWANTED]
}

出于某些原因,我不希望 ChildEntity 保留对其父项的引用。我只希望它保留 ParentEntity id 但仅此而已。 到目前为止,没问题,我只是删除了 [NOTWANTED] 行,一切都按预期进行。

我的问题是:如何在特定情况下禁用级联删除?

如果我仍然有父导航属性,它会很简单:

modelBuilder.Entity<ChildEntity>()
    .HasRequired(c => c.parent)
    .WithMany(p => p.Childrens)
    .WillCascadeOndelete(false)

但是,如果没有导航属性,我不知道如何实现在删除时禁用级联(当然不是全局禁用它,也不是每个表禁用它,只是为了关系)。

我现在所做的是将外键设置为可为空的 int,以禁用删除时的级联,但这并不漂亮:

public int? ParentEntityId; // Foreign Key - nullable just to disable cascade on delete

如何让它与 Fluent API 一起工作?认为这应该是可能的。

最佳答案

您必须从关联的另一端配置它:

modelBuilder.Entity<ParentEntity>()
    .HasMany(p => p.Children)
    .WithRequired()
    .HasForeignKey(c => c.ParentEntityId)
    .WillCascadeOnDelete(false);

关于c# - EF4.1 代码优先 : How to disable delete cascade for a relationship without navigation property in dependent entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9136255/

有关c# - EF4.1 代码优先 : How to disable delete cascade for a relationship without navigation property in dependent entity的更多相关文章

随机推荐