EF4.1代码首先:如何禁用级联删除在相关的实体没有导航财产有关系 [英] EF4.1 Code First : How to disable delete cascade for a relationship without navigation property in dependant entity
问题描述
下面是我的问题。
比方说,我有这两个非常基本的实体:
Here is my problem. 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]
}
对于一些原因,我不希望ChildEntity持有参考回到他的父母。我只是希望它保持ParentEntity ID,但仅此而已。
到现在为止,没有问题,我只是删除[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).
什么我现在做的是设置外键作为一个可空INT,以禁用删除级联,但是这并不漂亮:
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
任何想法我如何能得到它的工作用流利的API?认为应该是可能的...
Any idea how I can 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屋!