Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

c# - The object cannot be deleted because it was not found in the ObjectStateManager in entity framework 5

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();

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...