对象不能删除,因为它是在ObjectStateManager在实体框架5未找到 [英] The object cannot be deleted because it was not found in the ObjectStateManager in entity framework 5

查看:515
本文介绍了对象不能删除,因为它是在ObjectStateManager在实体框架5未找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图删除使用的EntityFramework 5的对象,但我得到这个错误。
对象不能被删除,因为它没有在ObjectStateManager发现的我使用

中的删除()方法 DeleteObject的()中不存在EF5。
谁能帮我缺少的是什么?

I'm trying to delete an object using EntityFramework 5 but i get this error. The object cannot be deleted because it was not found in the ObjectStateManager
I am using the Remove() method as DeleteObject() is not present in EF5. Can anyone help what am I missing?

这不适用于所有的工作。

This does not work for Remove

localDb.Customers.Remove(new Customer() { CustomerId = id });
                localDb.SaveChanges();



我从MSDN试图再就是状态更改为已删除。但在这里它提供了一个错误,说所有的字段应该存在。 ?是否有必要让那么完整记录删除

Another thing I tried from msdn to change the state to Deleted. But here it gives an error saying all the fields should be present. Is it necessary to get the complete record then delete?

var customer = new Customer(){ CustomerId = id };
                localDb.Customers.Attach(customer);

                localDb.Entry(customer).State = EntityState.Deleted;
                localDb.SaveChanges();



任何投入?

Any inputs?

推荐答案

您可以从数据库中读取行,然后将其删除,但是这会导致2往返到数据库。

You can fetch the row from the database and then delete it, but this causes 2 round trips to the database.

如果你想要做的它一击,你的第二个版本的连接将工作 - 只要实体尚未加载到上下文

If you want to do it in one hit, your second version with Attach will work - as long as the entity is not already loaded into the context.

你正在被它的任何数据库的写之前运行EF验证导致错误

The error you are getting is caused by EF validation which runs before any database write.

您可以暂时关闭它这样的:

You can turn it off temporarily like this:

bool oldValidateOnSaveEnabled = localDb.Configuration.ValidateOnSaveEnabled;

try
{
  localDb.Configuration.ValidateOnSaveEnabled = false;

  var customer = new Customer { CustomerId = id };

  localDb.Customers.Attach(customer);
  localDb.Entry(customer).State = EntityState.Deleted;
  localDb.SaveChanges();
}
finally
{
  localDb.Configuration.ValidateOnSaveEnabled = oldValidateOnSaveEnabled;
}

这篇关于对象不能删除,因为它是在ObjectStateManager在实体框架5未找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆