Unidirectional association with WillCascadeOnDelete

时光怂恿深爱的人放手 提交于 2019-12-10 10:49:10

问题


I have a very simple unidirectional class mappings.

public class MyDbContext : DbContext
{
    public MyDbContext() : base("CodeFirstDatabase")
    {

    }

    public DbSet<Contact> Contacts { get; set; }
    public DbSet<PhoneNumber> Number { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        modelBuilder.Entity<Contact>()
            .HasMany(c => c.Numbers)
            .WithOptional()
            //.Map(p => p.MapKey("ContactId"))
            .WillCascadeOnDelete(true);
    }
}

As you can see, Contact has a list of Numbers, but Number doesn't know anything about contact (it doesn't have a property on it's parent). What I'm trying to do here is to achieve the following: when number is removed from contact and saved using SaveChanges, I want that number row to be removed from database, but instead, EF sets the foreign key to null and the row remains in database. Any idea what's wrong?

Thanks.


回答1:


It's annoying, but EF does not offer any way to automatically delete orphans.

You have to manually delete the PhoneNumber instances (i.e. context.Number.Remove(theNumber).



来源:https://stackoverflow.com/questions/11475690/unidirectional-association-with-willcascadeondelete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!