如何过滤使用linq删除的实体到实体 [英] How to filter entities that are deleted using linq to entities

查看:86
本文介绍了如何过滤使用linq删除的实体到实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单一的DBContext,但由于某种原因,当实例在两个方法之间共享时,不会填充其他方法所做的更改。



例如: 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屋!

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