Expression.Call - Calling linq extension: FirstOrDefault, Where
Asked Answered
S

1

6

I am trying to create the following dynamically, however I am having problems calling the extension method FirstOrDefault:

 using(var context = new Entities())
 {
     var list = context.Engines.Include("Cars").Select(e => e.Cars.FirstOrDefault()).ToList();
 }

I have the following

Expression parameter = Expression.Parameter(typeof(Engine), "e");
Expression property = Expression.Property(parameter, "Cars");
  • parameter = {e}
  • property = {e.Cars}

Those are good, but I am encountering a problem when I try and call the FirstOrDefault method:

var result = Expression.Call(typeof(Queryable), "FirstOrDefault", new type[] { typeof(Car)}, property);

I would like to get

  • result = {e.Cars.FirstOrDefault()}

but I am getting an InvalidOperationException

No generic method 'FirstOrDefault' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

Any help would be much appreciated.

Scevo answered 7/10, 2010 at 20:13 Comment(2)
Can you clarify? FirstOrDefault isn't usually part of the lambda, so doesn't need to be involved with ExpressionTouchwood
My goal is to create a lambda inside a lamda, so something like this: .Where(e => e.Cars.Where(c => c.Name == "Honda").Count > 0) Does that clarify anything or am I confused?Scevo
T
12

Are you sure e.Cars is an IQueryable<T>?

If not, you can't pass it to Queryable.FirstOrDefault<T>(IQueryable<T>).

If it's an IEnumerable<T>, change your code to call Enumerable.FirstOrDefault<T>(IEnumerable<T>):

 var result =
     Expression.Call(
         typeof(Enumerable),
         "FirstOrDefault",
         new Type[] { TypeSystem.GetElementType(property.Type) },
         property);
Thought answered 7/10, 2010 at 20:26 Comment(4)
Thanks it works now. Do you know if there is a way to get the Car Type from the property expression?Scevo
@Aducci: TypeSystem.GetElementType ( property.Type )Thought
e.Cars.AsQueryable() was another solution I thinkPhare
What is TypeSystem? Uknown type.Lethia

© 2022 - 2024 — McMap. All rights reserved.