[英]EF4.1 Code First : How to disable delete cascade for a relationship without navigation property in dependent entity
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. 出于某些原因,我不希望ChildEntity将引用保留回其父级。 I just want it to keep the ParentEntity id but nothing more. 我只是希望它保留ParentEntity id,但仅此而已。 Up until now, no problem, I just delete the [NOTWANTED] line, and everything works as expected. 到目前为止,没问题,我只是删除[NOTWANTED]行,一切都按预期工作。
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: 我现在所做的是将外键设置为可以为空的int,以便在删除时禁用级联,但这并不漂亮:
public int? ParentEntityId; // Foreign Key - nullable just to disable cascade on delete
How can I get it to work with fluent API? 如何才能使用流畅的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.