简体   繁体   中英

Creating a generic get for foreign keys in EF Core

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?

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

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