EF4.1 Code First : How to disable delete cascade for a relationship without navigation property in dependent entity(EF4.1 代码优先:如何为依赖实体中没有导航属性的关系禁用删除级联)
问题描述
假设我有这两个非常基本的实体:
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 一起工作?觉得应该可以.
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 代码优先:如何为依赖实体中没有导航属性的关系禁用删除级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:EF4.1 代码优先:如何为依赖实体中没有导航属性的关系禁用删除级联
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01