【发布时间】:2013-10-07 15:49:20
【问题描述】:
我有 1 个 LINQ,它使用了这么多。我尝试创建返回此 LINQ 的方法,例如:
public static System.Linq.Expressions.Expression<Func<MyEntity, bool>> GetFilteredEntity() {
return x => true/*Some condition*/;
}
public static Func<MyEntity, bool> GetFilteredEntity() {
return x => true/*Some condition*/;
}
然后像这样使用
db.MyEntities.Where(GetFilteredEntity());
成功了,但是!我需要像这样使用它
db.ParentEntities.Where(entity => entity.MyEntities.Where(GetFilteredEntity()));
这段代码也编译过,但每次我使用它时,我都会收到错误:
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
,甚至:
db.ParentEntities.Where(entity => entity.MyEntities.Where(GetFilteredEntity())).ToList();
也抛出这个异常。
但是,
db.ParentEntities.Where(entity => entity.MyEntities.Where(x => true/*Some condition*/))
仍然可以正常工作! 那么为什么会发生这种情况,并且有办法解决这个问题?
最终工作代码
public static Expression<Func<MyEntity, bool>> GetFilteredEntity() {
return x => true/*Some condition*/;
}
和
var expression = GetFilteredEntity();
db.ParentEntities.Where(entity => entity.MyEntities.AsQueryable().Where(expression ));
也感谢.AsQueryable()Passing func as parameter in Linq to Entities and 'Internal .NET Framework Data Provider error 1025' error
【问题讨论】:
-
不相关的问题:这应该做什么?
db.ParentEntities.Where(entity => entity.MyEntities.Where(GetFilteredEntity()));ParentEntity是否派生自MyEntity? -
Nope =) 它只是将
ParentEntity过滤后的MyEntity计数大于...(也是问题和答案)