简体   繁体   中英

Calling a custom method in linq to Entities without AsEnumerable

Currently I have some Entity Framework code that looks like this:

return _context
           .MyData
           .OrderBy(x => x.Name)
           .Select(x => new CustomObject { Name = x.Name, Description = x.Description });

I would like to be able to move out the creation of my CustomObject code to a separate function, so something like this:

 return _context
           .MyData
           .OrderBy(x => x.Name)
           .Select(x => CustomObjectFactory.Create(x));

But when I do this I get the

Linq to entities does not recognise the method

error. I understand I can just chuck in a call to AsEnumerable() :

return _context
          .MyData
          .OrderBy(x => x.Name)
          .AsEnumerable()
          .Select(x => CustomObjectFactory.Create(x));

But I'd like to know how to do this without the extra AsEnumerable() call. I'm pretty sure it involves some kind of complex expression tree.

For bonus points, I'd also be interested in how to do this:

 return _context
            .MyData
            .OrderBy(x => x.Name)
            .CreateCustomObject()

You cannot do this, because until You call AsEnumerable all this code will be translated to database query. Code inside this select is not regular code, but an expression , that gets translated to sql statements. Database does not know Your custom methods - it knows only some of methods defined by Your entity framework vendor, with some libraries it is possible to call functions returning primitive types.

After calling AsEnumerable results of query are materialized, so You can use regular c# methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM