开发者

How do you re-use select statements with Entity Framework?

Given the following query:

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

How can I re-use the select part of the statement in other queries? I.e.

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

I tried just using a mapper method:

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

With:

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

But if I do this, then the framework throws an error such as:

LINQ to Entities does not recognize the method 'MapUser(TblUser)' method, and this method cannot be translated into a store expression.


You can't use regular function calls in a query definition like that. LINQ needs expression trees, it can't analyze compiled functions and magically translate that to SQL. Read this for a more elaborate explanation

The techniques used in the cited article are incorporated in linqkit (factoring out predicates) and might be of help, though I'm not sure you can use the same technique for managing projections, which is what you seem to want.

The more fundamental question you should ask yourself here IMHO is whether you really need this extra mapping layer? It seems like you're implementing something that EF is already perfectly capable of doing for you...


Try making your MapUser method static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜