Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When selecting an anonymous type with LINQ from EF, is there no way to run a method on an object as you select it?

Let's say I have a method:

bool myMethod(int a)
{
//return a bool
}

So let's say I the following

// assume a has prop1 and prop2 both ints
var mySelection = from a in myContainer 
                  where a=somecondition 
                  select new {
                         a.prop1,
                         myMethod(a.prop2)
                     };

Is there really no way to run myMethod in the anonymous type declaration? Is there some sort of trick?

Can I put an anonymous method in there to return the equivalent of myMethod(a.prop2)?

like image 727
Matt Avatar asked Dec 18 '22 04:12

Matt


1 Answers

Well lets separate this into LINQ to Objects and LINQ to Entities

In LINQ to Object the above fails because the compiler doesn't know what the Property name is, if you change it to this:

var mySelection = from a in myContainer
                  where a=somecondition 
                  select new {
                         a.prop1,
                         prop2 = myMethod(a.prop2)
                     };

It will work in LINQ to Objects

However the Entity Framework won't be able to translate the method call (unless it is a function known to the EF like a Model Defined Function, EdmMethods or SqlMethods) so you'll have to rewrite that query like this:

var mySelection = from a in myContainer
                  where a=somecondition 
                  select new {
                         a.prop1,
                         a.prop2
                     };

var myResults = from a in mySelection.AsEnumerable()
                select new {a.prop1, prop2 = myMethod(a.prop2)};

This pulls what you need out the database, and then using the AsEnumerable() call turns the call to myMethod into something processed by LINQ to Objects rather than LINQ to Entities

Hope this helps

Alex

like image 171
Alex James Avatar answered Dec 28 '22 09:12

Alex James