为什么这个动态表达在Entity Framework中失败了?

时间:2016-05-29 19:55:30

标签: c# entity-framework expression

我正在尝试构建一个动态的,可重用的WHERE子句表达式来评估Entity Framework中的两个连接对象。

以下是正确的孤立工作:

var result1 = dbContext.Entity1
  .Join(dbContext.Entity2,
    e1 => new {e1.SomeProperty, e1.AnotherProperty},
    e2 => new {e2.SomeProperty, e2.AnotherProperty},
    (e1, e2) => new JoinedEntity1Entity2 {Entity1 = e1, Entity2 = e2})
  .AsQueryable()
  .Where(JoinedEntity1Entity2Filter())
  .Select(entities => new FilteredEntity 
   { 
     a = entities.Entity1.A,
     b = entities.Entity2.B
   })       

JoinedEntity1Entity2Filter()看起来像这样:

public Expression<Func<JoinedEntity1Entity2, bool>> JoinedEntity1Entity2Filter()
{
    return joinedEntities =>
      joinedEntities.Entity1.SomeValue == joinedEntities.Entity2.SomeValue;
}

但是,当我尝试使用上面的查询作为另一个简单查询的子选择时,它会失败并且我收到错误。

例如:

var result2 = from x in dbContext.Entity3
    select new SomeObject 
    {
       // this the query from above
       FilteredEntities = dbContext.Entity1
                            .Join(dbContext.Entity2,
                               e1 => new {e1.SomeProperty, e1.AnotherProperty},
                               e2 => new {e2.SomeProperty, e2.AnotherProperty},
                               (e1, e2) => new JoinedEntity1Entity2 {Entity1 = e1, Entity2 = e2})
                            .AsQueryable()
                            .Where(JoinedEntity1Entity2Filter())
                            .Select(entities => new FilteredEntity 
                             { 
                                 a = entities.Entity1.A,
                                 b = entities.Entity2.B
                             })
    }

我得到的错误如下:

  

内部.NET Framework数据提供程序错误1025。

这是堆栈跟踪的顶部:

  

at System.Data.Objects.ELinq.ExpressionConverter.GetLambdaExpression(Expression argument)

非常感谢。

0 个答案:

没有答案