【问题标题】:How do you re-use select statements with Entity Framework?如何在 Entity Framework 中重用 select 语句?
【发布时间】:2010-08-01 20:07:49
【问题描述】:

给定以下查询:

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 to Entities 无法识别 方法'MapUser(TblUser)'方法, 而且这个方法不能翻译 到商店表达式中。

【问题讨论】:

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


    【解决方案1】:

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

    引用文章中使用的技术已包含在 linqkit(分解谓词)中,并且可能会有所帮助,但我不确定您是否可以使用相同的技术来管理预测,这似乎是您想要的.

    恕我直言,您应该在这里问自己的更基本的问题是您是否真的需要这个额外的映射层?看起来你正在实现一些 EF 已经完全有能力为你做的事情......

    【讨论】:

    • 这样说吧,我不想写User = new User() { UserId = item.User.UserId, UserName = item.User.Username, NField = item.User.etc } 大概30次。
    【解决方案2】:

    尝试将您的MapUser 方法设为static

    【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2017-04-07
    • 2020-08-30
    • 2020-06-02
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多