我有 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()
感谢在 Linq to Entities 中将 func 作为参数传递和“Internal .NET Framework Data Provider error 1025”错误