0

这是我删除对象的代码片段:

var foo = this.repository.GetFoo();

foreach (var item in foo.RelatedItems.ToList()) {
    if (x == y) {
        //Update happens here; this isn't executing however.
    } else {
        //This code block is executed; this is where I am telling the context to mark this object for deletion.
        foo.RelatedItems.Remove(item);
    }
}

this.repository.Save();

调用时.Save(),出现错误:“无法将值 NULL 插入列”。我使用分析器查看实际执行的 SQL 是:

update dbo.RelatedItems
set foreignKey = null
where id = X

我希望在这里执行删除语句,但是,由于某种原因,它试图通过将外键设置为 null 来更新记录。

编辑

我将以下代码添加到我的存储库类中以解决该问题:

public void DeleteItem(Item item) {
    context.Entry(item).State = System.Data.EntityState.Deleted;
}
4

1 回答 1

0

请参阅此相关问题:EF 4:从集合中删除子对象不会删除它 - 为什么?

Remove显然,在和Deletewhere之间存在语义差异,Remove将通过删除外键来孤立该行,并且Delete实际上会将记录从表中取出。

其他问题的用户vittore建议

dbcontext.DeleteObject(item);

循环内。

于 2012-10-25T15:21:56.287 回答