Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linq 如何在实体框架中重用select语句?_Linq_Entity Framework_Linq To Entities_C# 4.0_Entity Framework 4 - Fatal编程技术网

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

Linq 如何在实体框架中重用select语句?,linq,entity-framework,linq-to-entities,c#-4.0,entity-framework-4,Linq,Entity Framework,Linq To Entities,C# 4.0,Entity Framework 4,给出以下查询: 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.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
   };
}
与:

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

LINQ to实体无法识别 方法“MapUser(TblUser)”方法, 这种方法是无法翻译的 转换为存储表达式


尝试使用
MapUser
方法
static

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

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


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

嗯。。。似乎在L2S中修复了它,但在EF中没有。不过,您可能已经看过这篇文章了:这样说,我不想写大约30次
User=newuser(){UserId=item.User.UserId,UserName=item.User.UserName,NField=item.User.etc}
var query = from item in context.Users // Users if of type TblUser
            select MapUser(item);