Get entity by field value in ASP.NET Core 3.1

asp.net-core c# entity-framework-core linq-to-sql repository-pattern

Question

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().

1
0
12/18/2019 5:44:09 AM

Popular Answer

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());
}
2
12/18/2019 6:14:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow