EF4.1代码优先:如何禁用在依赖实体中没有导航属性的关系的删除级联 [英] EF4.1 Code First : How to disable delete cascade for a relationship without navigation property in dependent entity

查看:187
本文介绍了EF4.1代码优先:如何禁用在依赖实体中没有导航属性的关系的删除级联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class ParentEntity 
{
public int Id;
公共虚拟ICollection< ChildEntity>儿童;
}

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

由于某些原因,我不希望ChildEntity把参考资料留给他的父母。我只是希望它保持ParentEntity ID,但没有更多。
到目前为止,没有问题,我只是删除[NOTWANTED]行,一切正常。



这里的问题是:如何禁用在这种情况下级联删除?



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



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

但是,如果没有导航属性,我不知道如何实现在关闭的时候禁用级联(当然,不是每个表都禁用它,而只是关系)。

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

  public int? ParentEntityId; //外键 - 可以为空可以删除级联删除

如何使用流利API?认为它应该是可能的。

解决方案

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

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


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.

解决方案

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);

这篇关于EF4.1代码优先:如何禁用在依赖实体中没有导航属性的关系的删除级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆