Unidirectional association with WillCascadeOnDelet

2019-05-28 13:17发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-05-28 13:49

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).

查看更多
登录 后发表回答