问题
I have a singleton DBContext but for some reason when the instance is shared across 2 methods does not populate the changes made in other method.
Eg: Method1Delete2RowS() will delete 2 rows.Method2() reads all rows that are not deleted
My method 2 always shows deleted records too. Cause i have not accepted any changes yet.
I used something like this
context.Students.Where(x => context.ObjectStateManager.GetObjectStateEntry(x)
.State != System.Data.EntityState.Deleted);
but this code throws an exception that "GetObjectStateEntry()" cannot be recognized by LINQ.
How can I fix this?
回答1:
The exception is caused by the fact that EF tries to translate your LINQ query into SQL that's executed by the database. Of course there is no way to send the GetObjectStateEntry call to the database. You'll have to switch to linq-to-objects:
context.Students.AsEnumerable().Where(x => ...
Unfortunately in the ObjectContext API there's not an easy way to get undeleted entities.
In the DbContext API you can work with local collections, like
context.Students.Local
The local collection shows entities that were loaded by previous queries. The nice thing is that deleted entries are excluded from the local collection. Maybe an incentive for you to move to DbContext?
来源:https://stackoverflow.com/questions/20252606/how-to-filter-entities-that-are-deleted-using-linq-to-entities