【问题标题】:linq to entities does not recognize the methodlinq to entity 无法识别该方法
【发布时间】:2011-01-24 16:00:31
【问题描述】:

我有一个存储库类,它有一个返回 ObjectSet 的方法

类似

public class Repository:ObjectContext
{
  public IObjectSet<T> GetObjectSet()
  {...}
}

当我在查询中使用它时,我得到 linq to entity 错误(不识别方法...)

我喜欢这样的想法,即拥有一个不会每次都重新生成的通用存储库(使用 T4 模板) 有没有办法扩展查询提供程序以识别我的方法?但我确实想在服务器上解决它(换句话说,参与查询生成)。 使用它的示例代码是:

static readonly Func<Repository,
        string, AuthorizedUser>  getInstitutionByAuthorizedUserName = CompiledQuery.Compile(
          (ObjectContext ctx, string userName) =>
              (from inst in ctx.GetObjectSet<Institution>()
              join auths in ctx.GetObjectSet<AuthorizedUser>() 
              on inst.Key equals auths.Institution.Key
              where auths.Name == userName
              select inst.Key).SingleOrDefault();

【问题讨论】:

  • 您没有显示尝试使用它的代码,这使得弄清楚发生了什么变得更加困难......
  • 不识别哪种方法?
  • 它不识别 ctx.GetObjectSet() 方法

标签: c# entity-framework linq-to-entities


【解决方案1】:

不要重新发明CreateObjectSetbreak the join habit

static readonly Func<Repository,
    string, AuthorizedUser>  getInstitutionByAuthorizedUserName = CompiledQuery.Compile(
      (ObjectContext ctx, string userName) =>
          from inst in ctx.CreateObjectSet<Institution>()
          from auths in inst.Authorizations
          where auths.Name == userName
          select inst.Key).SingleOrDefault();
       );

【讨论】:

  • 第一个示例无法编译(带有语句体的 lambda 表达式无法转换为表达式树)。此外,我正在创建对象集并将其缓存,因为 ObjectContext 的生命周期已超过整个请求。
  • 不在你展示的代码中,你不是。无论如何,“缓存”ObjectSet 并没有什么好处。 OC 已经缓存了实例,ObjectSet 本身非常轻量级。 CompiledQuery, OTOH, 是有益的,你已经在这样做了。无论如何,第二个例子是更好的形式,所以如果第一个不起作用,没有损失。 :)
  • 第二个示例也无法编译(与第一个相同的错误)。同意你的加入不可读性
  • 好吧,该代码将在表达式之外工作(即普通方法,而不是CompiledQuery。在CompiledQuery 内,您可能需要传递objectSet。让我用另一个版本更新答案试试看。
  • 2 个问题,在编译查询中,第一个 arg 必须是 objectcontext,即使我这样做我也会得到“仅支持标量参数错误”..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
相关资源
最近更新 更多