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");
{e}
{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
{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.
FirstOrDefault<TSource>(IEnumerable<TSource>, TSource)Returns the first element of a sequence, or a specified default value if the sequence contains no elements.
FirstOrDefault: Returns the first element of a sequence, or a default value if no element is found. Throws exception: Only if the source is null. Use when: When more than 1 element is expected and you want only the first.
First. Returns the first element of a collection, or the first element that satisfies a condition. FirstOrDefault. Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With