我有一个名为“Notaries”的表:
NotaryID int,
NotaryName nvarchar(MAX)
和名为“NotaryPhones”的表:
PhoneID int,
NotaryID int,
PhoneNumber nvarchar(50)
因此,关系是“一对多”的。现在我想清除所有电话,这取决于公证人。我的代码:
Notary.Models.Notary notary = (from i in db.Notaries where i.NotaryID == model.NotaryID.Value select i).FirstOrDefault();
notary.CityID = Convert.ToInt32(model.City.SelectedItem);
notary.NotaryPhones.Clear();
db.SaveChanges();
但是我得到一个错误:
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.
如果我删除字符串
notary.NotaryPhones.Clear();
它有效。我明白,这是一件微不足道的事情,但不明白如何解决它
最佳答案
发生的事情是你的 notary.NotaryPhones.Clear();
正在从您的 NotaryPhone
中删除外键引用表到你的Notary
table 。因为这被设置为不可为 null 的 key ,所以您没有孤立的电话记录,所以您会收到该错误。
您要做的是在您的存储库中设置一个方法,该方法将调用 context.NotaryPhones.Remove(**instance variable pointing to one of the phones to delete**);
这将从数据库中删除它们。
澄清
它删除外键引用的原因是 notary.NotaryPhones.Clear()
只是从 notary
中删除这些对象目的。这些对象将继续以您编写的方式存在。
所以当.Clear()
被执行,它需要你的 phone.NotaryID
属性并删除指向 notary
的 ID 指针.由于您没有为其分配任何其他内容,因此它尝试分配的值是 null
(唯一不可能指向 Notary
对象的值)。但是,因为您已将其设置为 int
,而不是 int?
,它无法进行该分配,并且会抛出您看到的错误。
您说您正在尝试删除对象,因此您需要将它们从数据库中删除。为此,您需要按照我上面的说明进行操作。
关于c# - Entity Framework 子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044079/