使用Fluent API进行级联删除
我有两个实体。 Profile
和ProfileImages
。 获取Profile
我想通过Profile
删除ProfileImages
而不删除对Profile
的引用(将其设置为null
)。 如何通过流畅的API和级联删除来完成? 我是否设置了HasRequired
属性或CascadeDelete
属性?
public class Profile { //other code here for entity public virtual ICollection 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 Context
:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .HasOptional(c => c.ProfileImages) .WithOptionalDependent() .WillCascadeOnDelete(true); }
在此处阅读更多内容: Enabling Cascade Delete
您可以使用WillCascadeOnDelete方法在关系上配置级联删除。 如果依赖实体上的外键不可为空,则Code First会在关系上设置级联删除。 如果依赖实体上的外键可以为空,则Code First不会在关系上设置级联删除,并且当删除主体时,外键将设置为null。
上述就是C#学习教程:使用Fluent API进行级联删除分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1012291.html