代码之家  ›  专栏  ›  技术社区  ›  djdd87

如何在实体框架中重用select语句?

  •  3
  • djdd87  · 技术社区  · 14 年前

    给出以下查询:

    var query = from item in context.Users // Users if of type TblUser
                select new User()          // User is the domain class model
                {
                    ID = item.Username,
                    Username = item.Username
                };
    

    如何在其他查询中重用语句的select部分?即。

    var query = from item in context.Jobs  // Jobs if of type TblJob
                select new Job()           // Job is the domain class model
                {
                    ID = item.JobId,
                    User = ReuseAboveSelectStatement(item.User);
                };
    

    我尝试使用映射器方法:

    public User MapUser(TblUser item)
    {
       return item == null ? null : new User()
       {
          ID = item.UserId,
          Username = item.Username
       };
    }
    

    var query = from item in context.Users // Users if of type TblUser
                select MapUser(item);
    

    但如果我这样做,那么框架会抛出一个错误,例如:

    LINQ到实体不识别 这个方法不能翻译

    2 回复  |  直到 14 年前
        1
  •  1
  •   jeroenh    14 年前

    不能在这样的查询定义中使用常规函数调用。LINQ需要表达式树,它不能分析编译后的函数并将其神奇地转换为SQL。 Read this for a more elaborate explanation

    linqkit (分解出谓词)可能会有所帮助,不过我不确定您是否可以使用相同的技术来管理投影,这似乎是您想要的。

    更基本的问题是你是否真的需要这个额外的映射层?似乎你正在实现EF已经完全有能力为你做的事情。。。

        2
  •  0
  •   Yakimych    14 年前

    试着让你的 MapUser 方法 static