EF4.1 Code First:如何禁用依赖实体中没有导航属性的关系的删除级联

发布于 2025-01-02 07:43:41 字数 917 浏览 4 评论 0原文

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

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)

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

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

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

如何让它与 Fluent API 一起工作?觉得应该是可以的。

Let's say I have these two very basic entities:

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

For some reasons, I don't want the ChildEntity to hold a reference back to his parent. I just want it to keep the ParentEntity id but nothing more.
Up until now, no problem, I just delete the [NOTWANTED] line, and everything works as expected.

My problem here is: how to disable the cascade delete in that specific case?

If I still had the parent navigation property it would be as easy as:

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

However without the navigation property I have no idea how I can achieve to disable the cascade on delete (without disabling it globally of course, nor per table, but just for the relation).

What I have done right now is to set the foreign key as a nullable int, in order to disable the cascade on delete, but that's not pretty:

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

How can I get it to work with fluent API? Think it should be possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2025-01-09 07:43:41

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

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

You must configure it from the other side of the association:

modelBuilder.Entity<ParentEntity>()
    .HasMany(p => p.Children)
    .WithRequired()
    .HasForeignKey(c => c.ParentEntityId)
    .WillCascadeOnDelete(false);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文