简体   繁体   中英

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:

The primary key value cannot be deleted because references to this key still exist. [ Foreign key constraint name = FK_dbo.Persons_dbo.Contacts_ContactsId ]

I set the ContactId to int? so it could be nullable, and the database says it's a nullable FK, and it works fine in general. 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. 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.
So make sure when you delete Contact all it's dependent Person entities have been loaded.

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