使用Fluent API进行级联删除 [英] Cascade delete using Fluent API
问题描述
我有两个实体。 个人资料
和 ProfileImages
。提取个人资料
后,我要通过个人资料
删除 ProfileImages
没有它,只需删除对个人资料
的引用(将其设置为 null
)。如何使用流畅的API和级联删除?是否要设置具有必需的
属性或 CascadeDelete
属性?
I have two entities. Profile
and ProfileImages
. After fetching a Profile
I want to delete ProfileImages
through Profile
without it just removing the reference to Profile
(setting it to null
). How can this be done with fluent API and Cascading Delete? Do I set the HasRequired
attribute or the CascadeDelete
attribute?
public class Profile
{
//other code here for entity
public virtual ICollection<ProfileImage> ProfileImages { get; set; }
}
public class ProfileImage
{
// other code here left out
[Index]
public string ProfileRefId { get; set; }
[ForeignKey("ProfileRefId")]
public virtual Profile Profile { get; set; }
}
推荐答案
您可以将其添加到您的 DB上下文
:
You can add this to your DB Context
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Profile>()
.HasOptional(c => c.ProfileImages)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
在此处了解更多信息: 启用级联删除
Read more here:Enabling Cascade Delete
您可以使用
WillCascadeOnDelete方法在关系上配置级联删除。如果从属实体
上的外键不可为空,则Code First将在
关系上设置级联删除。如果从属实体上的外键可以为空,则
Code First不会在关系上设置级联删除,并且当删除
主体时,外键将设置为null。
You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.
这篇关于使用Fluent API进行级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!