Home > Mobile >  Creating a generic get for foreign keys in EF Core
Creating a generic get for foreign keys in EF Core

Time:09-05

I have this function

public static async Task<Response> GetGeneralizedAsync<T>(int id, string key)
            where T : class
        {
            using var context = new Context();
            var prop = typeof(T).GetProperty(key);

            var list = await context.Set<T>().AsAsyncEnumerable().Where(x => prop.GetValue(x) == (object)id).ToListAsync();
            return new Response(StatusCodes.Status200OK, list);
        }

However it only works while using client side evaluation, and I'm worried about performance as this would be a very core function. Is it possible to do the same thing, but have it evaluate on the server, or at least improve the performance?

CodePudding user response:

The Queryable.Where() method expects a Expression<Func<TSource,bool>> expression, which is used to "evaluate" which entities should be returned when applied on the Set<T> instance. You can define your method that such an expression must be provided instead of the id and key values you have used. The method can look like this:

public static async Task<Response> GetGeneralizedAsync<T>(Expression<Func<T, bool>> predicate)
        where T : class
{
    using var context = new Context();

    var list = await context.Set<T>().Where(predicate)).ToListAsync();
    return new Response(StatusCodes.Status200OK, list);
}

Then you use it like this:

GetGeneralizedAsync<People>(p => p.Age == 38);
  • Related