3

考虑以下查询:你如何在Entity Framework中重用select语句?

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 
      }; 

我怎样才能重新使用在其他的查询语句的选择部分?即

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)'方法, 并且此方法不能将 转换成存储表达式。

回答

1

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

的引用的文章中所使用的技术纳入linqkit(分解出谓词)和可能的帮助,虽然我不知道你可以使用同样的技术,用于管理的预测,这是你仿佛想。

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

+2

把它这样,我不想写'User = new User(){UserId = item.User.UserId,UserName = item.User.Username,NField = item.User.etc}'大约30次。 – GenericTypeTea 2010-08-03 07:52:08

0

试着制作你的MapUser方法static

+0

没有什么区别。 – GenericTypeTea 2010-08-01 20:55:26

+0

嗯...似乎将它固定在L2S中,但不是在EF中。你可能会看看这篇文章,但:http://blogs.msdn.com/b/efdesign/archive/2008/10/08/edm-and-store-functions-exposed-in-linq.aspx – Yakimych 2010-08-01 22:02:23