简体   繁体   中英

EF Multiple foreign keys only 1 required

I have an entity that defines properties for a number of different entityies.

eg.

class user{
ICollection<PropertyEntity> properties {get;set;}
}

class company{
ICollection<PropertyEntity> properties {get;set;}
}

When I delete a PropertyEntity from either User or Company.

myUser.properties.Remove(someProperty);

The PropertyEntity isn't deleted, it just has it's foreign key set to null.

I understand I could just use the [Key] annotation to define the foreign key. But presumably that would require both keys instead of either?

How do I get EF to structure that relationship so that either a User or Company can have many PropertyEntitys. But PropertyEntity is deleted if it doesn't have a User or Company?

If the relationship is optional there is no way to define the relationship so that removing a child from the navigation collection would also delete it from the database.

You have to either call DbSet<T>.Remove for the child...

myUser.properties.Remove(someProperty);
if (!someProperty.CompanyId.HasValue)
    context.PropertyEntities.Remove(someProperty);

... (which will also automatically remove the child from the collection) or you can try to delete "orphaned" children in an overridden SaveChanges before the changes are committed:

public override int SaveChanges()
{
    PropertyEntities.Local
        .Where(p => !p.UserId.HasValue && !p.CompanyId.HasValue)
        .ToList()
        .ForEach(p => PropertyEntities.Remove(p));

    return base.SaveChanges();
}

This approach is explained in more details on Arthur Vickers' blog .

Setting up an identifying relationship (which would support that the child is deleted from the database when it is removed from the navigation collection) would indeed only be possible if the relationship is required, so it's not an option for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM