我注意到我一直删除一个实体,它的关系并没有像预期的那样从Db中删除。我通过加载集合来解决这个问题,然后删除它们,就像这样
context.Entry(blog).Collection(p => p.Posts).Load();
我的问题是:基于this article,考虑到Lazy Loading已正确启用,我为什么要加载()我的实体关系以保证它们也会被删除?或者......我可能做错了吗?!
类
public partial class Profile
{
public long ProfileId { get; set; }
public string ProfileName { get; set; }
public Profile()
{
this.Roles = new HashSet<Role>();
}
public virtual ICollection<Role> Roles { get; set; }
}
public partial class Role
{
public string RoleId { get; set; }
public string Name { get; set; }
public Role()
{
this.Profiles = new HashSet<Profile>();
}
public virtual ICollection<Profile> Profiles { get; set; }
}
关系配置
modelBuilder.Entity<Profile>()
.HasMany<Role>(r => r.Roles)
.WithMany(p => p.Profiles)
.Map(pr =>
{
pr.MapLeftKey("ProfileId");
pr.MapRightKey("RoleId");
pr.ToTable("ProfileRole");
});
控制器
public ActionResult Profile_Destroy([DataSourceRequest]DataSourceRequest request, Profile profile)
{
if (ModelState.IsValid)
{
var currentProfile = db.Profile.Find(profile.ProfileId);
//Removing this line, Roles are NOT removed from deleted Profile.
db.Entry(currentProfile).Collection(cp => cp.Roles).Load();
db.Profile.Attach(currentProfile);
db.Profile.Remove(currentProfile);
db.SaveChanges();
}
}
此致