简体   繁体   English

EF仅需多个外键

[英]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. 当我从用户或公司中删除PropertyEntity时。

myUser.properties.Remove(someProperty);

The PropertyEntity isn't deleted, it just has it's foreign key set to null. PropertyEntity不会被删除,只是将其外键设置为null。

I understand I could just use the [Key] annotation to define the foreign key. 我知道我可以只使用[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. 我如何获得EF来构建该关系,以便用户或公司可以具有许多PropertyEntity。 But PropertyEntity is deleted if it doesn't have a User or Company? 但是,如果PropertyEntity没有用户或公司,则会将其删除?

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... 您必须调用DbSet<T>.Remove 。为孩子DbSet<T>.Remove ...

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: ...(这也会自动从集合中删除该子项),或者您可以在提交更改之前尝试删除覆盖的SaveChanges中的“孤立”子项:

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 . Arthur Vickers的博客上对此方法进行了更详细的说明。

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. 确实只有在需要这种关系的情况下,才可能建立标识关系 (这将支持在从导航集合中删除该子项时将其从数据库中删除),因此这不是您的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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