How to filter entities that are deleted using linq to entities

ⅰ亾dé卋堺 提交于 2019-12-11 02:45:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!