none
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[Project.RoleModel] ToList[RoleModel] RRS feed

  • Question

  • I have the following EF 5.0 query:
    var users = context.Users.Include(x => x.Roles).Select(x =>
      new UserModel {
        Id = x.Id,
        Roles = x.Roles.Select(y => (RoleModel)y.Id).ToList(),
        Username = x.Username
      });
    When I run this query I get the error:

    LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[Project.RoleModel] ToList[RoleModel](System.Collections.Generic.IEnumerable1[Project.RoleModel])' method, and this method cannot be translated into a store expression.

    RoleModel is an enum ... How to make this work?
    Tuesday, October 15, 2013 4:17 PM

Answers

  • Hello,

    As far as I know, the error message “LINQ to Entities does not recognize the method 'xxx' method, and this method cannot be translated into a store expression” will be thrown when an incompatible call is made.

    Because LINQ to Entities works by translating LINQ queries to SQL queries, then executing the resulting query on the database and converting the result back to application entities. Because of this crossover of two languages, it will only work when SQL-compatble method calls are made.

    For example the following code will throw this exception:

    var orders = db.Orders.Include("OrderDetails").Select(o => new { ID = o.OrderID, ODID = o.OrderDetails.Select(od => Convert.ToInt32(od.OrderDetailCode)) }).ToList();

    The following code will be ok:

    var orders = db.Orders.Include("OrderDetails").ToList().Select(o => new { ID = o.OrderID, ODID = o.OrderDetails.Select(od => Convert.ToInt16(od.OrderDetailCode)).ToList() });

    The only difference is that ToList() (or any other method that will execute an IQueryable) is called first that brings the Users data into .NET memory, with the subsequent Convert option done aftewards.

    The blog of Andrew den Hertog explains it excellently:

    http://www.andrewdenhertog.com/c/linq-to-entities-does-not-recognize-the-method-xxx-method-and-this-method-cannot-be-translated-into-a-store-expression/

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, October 16, 2013 5:46 AM
    Moderator