I had an issue where I changed my datasource from a bindingsource to an entity framework query.
var query = dataSource as IQueryable;
var value = query.Where("prop = @0", value).Cast<object>().SingleOrDefault();
With entity framework this throw an exception `Unable to cast the type 'customer' to type 'object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
The class where my code was did not have a reference to the lib with the model so ...Cast<customer>
was not possible.
Anyway I used this approach
var query = dataSource as IQueryable;
var targetType = query.GetType().GetGenericArguments()[0];
var value = query.Where("prop = @0", value).SingleOrDefault(targetType);
in conjunction with an IEnumerable extension which uses reflection
public static object SingleOrDefault(this IEnumerable enumerable, Type type)
{
var method = singleOrDefaultMethod.Value.MakeGenericMethod(new[] { type });
return method.Invoke(null, new[] { enumerable });
}
private static Lazy<MethodInfo> singleOrDefaultMethod
= new Lazy<MethodInfo>(() =>
typeof(Extensions).GetMethod(
"SingleOrDefault", BindingFlags.Static | BindingFlags.NonPublic));
private static T SingleOrDefault<T>(IEnumerable<T> enumerable)
{
return enumerable.SingleOrDefault();
}
feel free to implement caching per type to improve performance.
IEnumerable<T>
soImageList
could derive fromIEnumerable<Image>
? – Mclendon