Using Methods in Linq Projection

Given the following code:

        var EmployeeXPosition = from emp in context.WTDEmployee
                                from ep in emp.WTDEmployeeXOXPosition
                                select new { 
                                    EmployeeId = emp.id, 
                                    FullNameAndPosition =  string.Format("{0} {1} : {2}", emp.FirstName, emp.LastName, ep.WTDPosition.Position) 
                                };

It gives an error:

LINQ to Entities does not recognize the 'System.String Format (System.String, System.Object, System.Object, System.Object)' method, and this method cannot be translated into a storage expression.

Of course I could do:

 emp.FirstName+" "+ emp.LastName +" : " + ep.WTDPosition.Position

But it just looks ugly, any suggestions on how to use it string.Formatinstead?

+3
source share
2 answers

I usually solve this by creating two statements: one in LinqToEntities (or ToSql or something else), and then the other in LinqToObjects. I do what I need to do in the store, and then I do a separate processing step with objects in memory. It mixes the best of both worlds.

 var EmployeeXPosition = from emp in context.WTDEmployee
                                from ep in emp.WTDEmployeeXOXPosition
                                select new { 
                                    emp.id, 
                                    emp.FirstName, 
                                    emp.LastName,
                                    ep.WTDPosition.Position
                                };

var result = from item in EmployeeXPosition.ToList()
             select new 
             {
                EmployeeId = item.id, 
                FullNameAndPosition =  string.Format("{0} {1} : {2}", item.FirstName, item.LastName, item.Position) 
             };
+5

codeplex , , . , ,

LINQ Expression Projection , - LINQ ( ), lambda , .

+1

Source: https://habr.com/ru/post/1765911/


All Articles