I have used a method like this before to retrieve the entity and It was working perfectly in ASP.NET Core 2.2 Repository (because most of my tables have the CODE property):
public T GetByCode(string code)
{
PropertyInfo pi = typeof(T).GetProperty("Code");
return _context.Set<T>().FirstOrDefault(t => pi.GetValue(t).ToString().Trim().ToLower() == code.Trim().ToLower());
}
But as soon as I changed the framework to .NET Core 3.1 I got error like:
InvalidOperationException: The LINQ expression 'DbSet .Where(c => __pi_0.GetValue(c).ToString().Trim().ToLower() == __ToLower_1)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().
Because in EF Core 2.2, you were probably fetching the entire table into memory.
In your case, since all these tables have a Code
property, I would recommend adding some form of IHaveCode
common interface. Then you can trivially remove all the reflection, which EF Core can't translate to sql;
public T GetByCode<T>(string code) where T:IHaveCode
{
return _context.Set<T>().FirstOrDefault(t => t.Code.Trim().ToLower() == code.Trim().ToLower());
}