When choosing 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 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 a way to run myMethod in an anonymous type declaration? Is there any trick?

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

+4
source share
2 answers

Well allows you to split it into LINQ into objects and LINQ into objects

In LINQ to Object, the above does not work because the compiler does not know what the name of the property is if you changed it to this:

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

He will work in LINQ to Objects

However, the Entity Framework will not be able to translate the method call (unless it is a function known by EF as a function defined by Model, EdmMethods or SqlMethods), so you will have to rewrite this query as follows:

 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 will pull out what you need from the database, and then using the AsEnumerable () call turns the myMethod call into something LINQ handled for the objects, not LINQ to Entities

Hope this helps

Alex

+11
source

I don’t think there is a way to call a method from an anonymous initializer. Even if it were possible, it probably would not work very well.

If you need to create a result set that requires additional processing, I would create a specific class.

+1
source

All Articles