[英]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
. 我加载一个
Person
并清除其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
. 在上方,您可以看到加载
Person
并清除其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. 实际上,我想清除所有
Person.Phones
并添加一些新项目。 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. 您无法在EF中生成基于集合的SQL。 So there's no way in EF to generate a single SQL statement that deletes all
Phone
records given a Person.Id
. 因此,EF中无法生成单个SQL语句来删除给定
Person.Id
所有Phone
记录。
You can write the SQL yourself and pass it to either ObjectContext.ExecuteStoreCommand or DbContext.Database.ExecuteSqlCommand depending on your model. 您可以自己编写SQL, 然后根据模型将其传递给ObjectContext.ExecuteStoreCommand或DbContext.Database.ExecuteSqlCommand 。
foreach(var phone in person.Phones)
{
context.DeleteObject(phone);
}
person.Phones.Clear();
may help. 可能会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.