Reputation: 2116
This line of code:
db.Set<T>().Max(d => d.GetType().GetProperty("DateTimePropertyName").GetValue(d))
causes this exception:
LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method
How do I make it work?
Upvotes: 0
Views: 427
Reputation: 29836
Your trying to run c# code that's suppose to get translated into SQL somehow and can't.
This is a good guide to start with.
You have two options:
1.Fetch the data from the DB and go through it with LINQ to Objects - Probally the easiest and not the best way to do things since some queries can return large collections.
2.Try to find a better way to do what you are doing. Why would you want this reflection code to run? What's the purpose? Is the DateTimePropertyName non public? If so why? Otherwise something like this should work:
db.Set<T>().Max(d => d.DateTimePropertyName);
Upvotes: 1
Reputation: 12618
By default it assumes that you pass Expression<Func<T,TResult>>
, but what you need is to pass Func<T,TResult>
:
Func<T, object> f = p => p.GetType().GetProperty("DateTimePropertyName").GetValue(p);
_context.Set<T>().Max(f);
It comes from IEnumerable, so it will hit performance if you table is large
Upvotes: 0