如何过滤使用linq删除的实体到实体 [英] How to filter entities that are deleted using linq to entities
问题描述
例如: Method1Delete2RowS()
将删除2行。
Method2()
读取所有未被删除的行
我的方法2总是显示已删除的记录。因为我还没有接受任何修改。
我使用这样的东西
context.Students.Where x => context.ObjectStateManager.GetObjectStateEntry(x)
.State!= System.Data.EntityState.Deleted);
但是这个代码抛出一个异常,GetObjectStateEntry()不能被LINQ识别。 >
我如何解决这个问题?
该EF尝试将您的LINQ查询转换为由数据库执行的SQL。当然,没有办法将 GetObjectStateEntry
调用发送到数据库。你必须切换到linq对象:
context.Students.AsEnumerable()。Where(x => ; ...
不幸的是在 ObjectContext
API没有一个简单的方法来获取未删除的实体
在 DbContext
API中,您可以使用本地集合,如
context.Students.Local
本地集合显示由先前查询加载的实体,好的是删除的条目从本地集合中排除,也许是激励您移动到 DbContext
?
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?
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
?
这篇关于如何过滤使用linq删除的实体到实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!