简体   繁体   English

Entity Framework 6 CF:删除一对多

[英]Entity Framework 6 CF: Remove One-to-Many

My classes are something like:我的课程是这样的:

public class Contact
{
    public string Name { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
    [Key]
    public int Id { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public virtual Contact Contact { get; set; }
    public int? ContactId { get; set; }
    [Key]
    public int Id { get; set; }
}

When I try to remove a Contact that has in it's collection a Person , I get this error:当我尝试删除其集合中包含PersonContact ,我收到此错误:

The primary key value cannot be deleted because references to this key still exist.无法删除主键值,因为对该键的引用仍然存在。 [ Foreign key constraint name = FK_dbo.Persons_dbo.Contacts_ContactsId ] [外键约束名称 = FK_dbo.Persons_dbo.Contacts_ContactsId ]

I set the ContactId to int?我将ContactId设置为int? so it could be nullable, and the database says it's a nullable FK, and it works fine in general.所以它可以为空,并且数据库说它是一个可以为空的 FK,并且它通常可以正常工作。 Just when I try to delete the entity with the collection that I get this error.就在我尝试删除带有集合的实体时,我收到此错误。

I want to be able to delete a Contact, but not the Persons inside it , what should I do?我希望能够删除联系人,但不能删除其中的人员,我该怎么办?

The default behaviour of EF is to null foreign keys when their principal relationship is deleted. EF 的默认行为是在删除它们的主体关系时将外键设为空。 However, no database rule will be setup.但是,不会设置任何数据库规则。 In order for EF to issue update statements on the foreign keys of the dependents, they will need to be loaded into the context.为了让 EF 对依赖项的外键发出更新语句,需要将它们加载到上下文中。
So make sure when you delete Contact all it's dependent Person entities have been loaded.因此,请确保当您删除Contact所有依赖的Person实体都已加载。

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

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