开发者

Is the Entity Framework unable to use non-entity classes in a query?

I am trying to determine if I am doing something wrong, or if the Entity Framework just isn't meant to do this. I want to perform a LINQ style query to populate an object, including lists of child elements. In Linq2SQL this is valid, and is converted into an efficient SQL query whose results populate the new list.

class ReportItem
{
    string Manager; /* ... */ 
    List<string> Employees; /* ... */
}

var report = (from manager in entities.Managers
                select new ReportItem()
                {
                    Manager = manager.Name,
                    Employees = manager.Employees.Select(e => e.Name).ToList()
                }).ToList();

With the Entity Framework the Employees line will result in a method cannot be translated into a store expression error - the Entity Framework doe开发者_如何学Gos not seem to like constructing non-entity classes inside a LINQ statement, even though it does not involve any database side logic.

I understand that for change tracking entity classes are used, but is it not possible to read information into arbitrary classes? I don't want to construct entities and database views for every possible read scenario, and I don't want to send half the database across the pipe (entire Employee or Manager entities) just to read off something like the name property.

Is it possible to do this kind of 'lazy but efficient' query with the Entity Framework, or is the Entity Framework just not built with it in mind? I have already come across a number of issues converting a project from Linq2SQL to the Entity Framework, and this could really kill the deal.


LINQ to Entities only supports parameterless constructors and Initializers.
To be more specific, by design, LINQ to Entities requires the whole LINQ query expression to be translated to a server query. Only a few uncorrelated subexpressions (expressions in the query that do not depend on the results from the server) are evaluated on the client before the query is translated. Arbitrary method invocations that do not have a known translation, and parameterized initializers in your case, are not supported.

That said, what you are looking for could be easily accomplished by a Anonymous type Projection:

var report = (from manager in entities.Managers
              select new 
              {
                  Manager = manager.Name,
                  Employees = manager.Employees.Select(e => e.Name)
              })
              .ToList();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜