C# 未处理无效的操作异常
我正在尝试从实体中删除记录 出现错误:操作异常无效 无法删除该对象,因为在ObjectStateManager中找不到该对象 代码是这样的。。。C# 未处理无效的操作异常,c#,linq,entity-framework,linq-to-entities,C#,Linq,Entity Framework,Linq To Entities,我正在尝试从实体中删除记录 出现错误:操作异常无效 无法删除该对象,因为在ObjectStateManager中找不到该对象 代码是这样的。。。 private void btnProdDelete_Click(object sender, EventArgs e){ Image image = pictureBox1.Image; byte[] bit = null; bit = imageToByteArray(image); //var c = new categor
private void btnProdDelete_Click(object sender, EventArgs e){
Image image = pictureBox1.Image;
byte[] bit = null;
bit = imageToByteArray(image);
//var c = new category {
// category_Name = tbCategoryName.Text,
// category_Description = tbCategoryDescription.Text
//};
product pd = new product();
pd.product_Id = productid;
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;
tsgentity.DeleteObject(pd);
this.Close();
}
有谁能帮上忙吗
修改代码:
var pd =
new product()
{
product_Id = productid,
EntityKey = new EntityKey("product.id", "id", productid)
};
tsgentity.Attach(pd);
tsgentity.DeleteObject(pd);
问题是您正在尝试删除上下文未跟踪的对象 不获取而删除的正确方法是创建一个实例(实际上只需要id),将其附加到上下文,然后删除它:
正在初始化的
tsgentity
在哪里?错误表明您试图删除的对象与ObjectContext
没有正确关联。问题的可能重复是您正在创建一个新实体,然后试图删除它…因此如何删除而不是创建新实体…现在我遇到了这个错误:一个具有null EntityKey的对象值不能附加到对象上下文。在这一行,请附上(pd);你能看看这个吗?我也更新了我的答案,但是你可能需要根据你的需要调整它
var pd =
new product()
{
product_Id = productid,
EntityKey = new EntityKey("product.id", "id", productid)
};
tsgentity.Attach(pd);
tsgentity.DeleteObject(pd);