简体   繁体   中英

Reflection in Linq

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?

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM