简体   繁体   中英

deleting related entities in a one-to-many relationship

I have this domain:

public class Phone {
    public int Id { get; set; }
    public string Number { get; set; }
    public Person Person { get; set; }
}
public class Person {
    public int Id { get; set; }
    public IList<Phone> Phones { get; set; }
}

I load a Person and clear its Phones . But the operation cause an error:

// actually loads person from repository...
var person = _personRepository.Include(p => p.Phones).Where(p => p.Id == 1).First();
person.Phones.Clear();
_personRepository.Update(person);

Above you can see the simpled logic of loading a Person and clearing its Phones . But this error occurs:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

Actually I want to clear all of Person.Phones and add some new items. But I want to clearing them in one query, not delete them one by one.

Have you any idea? Can you help me please? Thanks in advance.

You can't generate set based SQL in EF. So there's no way in EF to generate a single SQL statement that deletes all Phone records given a Person.Id .

You can write the SQL yourself and pass it to either ObjectContext.ExecuteStoreCommand or DbContext.Database.ExecuteSqlCommand depending on your model.

foreach(var phone in person.Phones)
{
   context.DeleteObject(phone);
}
person.Phones.Clear();

may help.

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