gpt4 book ai didi

c# - 如何在 C# 中使用 DbContext 删除对象?

转载 作者:太空狗 更新时间:2023-10-30 00:18:47 24 4
gpt4 key购买 nike

我有这个删除方法:

private void btnDeleteOrderLine_Click(object sender, EventArgs e)
{
OrderLine orderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;
db.OrderLines.Remove(orderLine);
db.SaveChanges();
refreshGrid();
}

当我点击那个删除按钮时,我得到这个错误:

The object cannot be deleted because it was not found in the ObjectStateManager.

我发现这是因为 Context 类有两个实例。所以,我尝试了这个:

private void btnDeleteOrderLine_Click(object sender, EventArgs e)
{
OrderLine orderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;
db.OrderLines.Attach(orderLine); // added this part
db.OrderLines.Remove(orderLine);
db.SaveChanges();
refreshGrid();
}

然后这给了我以下错误:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

如何修复此问题并从 Context DbSet 中删除对象?

最佳答案

您必须先从上下文中找到该项目,然后将其删除。我使用了一个名为 Id 的属性。情况可能并非如此。您必须在那里设置相应的关键属性。

var selectedOrderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;

// Here using the context class we try to find if there is the
// selected item at all
var orderLine = db.OrderLines.SingleOrDefault(item => item.Id == selectedOrderLine.Id);

if(orderLine!=null)
{
// The items exists. So we remove it and calling
// the db.SaveChanges this will be removed from the database.
db.OrderLines.Remove(orderLine);
db.SaveChanges();
refreshGrid();
}

现在让我们更深入一点,以便我们理解以下错误消息:

The object cannot be deleted because it was not found in theObjectStateManager.

ObjectStateManager 类是什么?根据MSDN :

ObjectStateManager tracks query results, and provides logic to mergemultiple overlapping query results. It also performs in-memory changetracking when a user inserts, deletes, or modifies objects, andprovides the change set for updates. This change set is used by thechange processor to persist modifications.

除上述之外:

This class is typically used by ObjectContext and not directly inapplications.

关于c# - 如何在 C# 中使用 DbContext 删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018282/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com