简体   繁体   English

在 EF Core 中为外键创建通用获取

[英]Creating a generic get for foreign keys in EF Core

I have this function我有这个 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.但是它只在使用客户端评估时有效,我担心性能,因为这将是一个非常核心的 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. Queryable.Where()方法需要一个Expression<Func<TSource,bool>>表达式,该表达式用于“评估”在应用于Set<T>实例时应返回哪些实体。 You can define your method that such an expression must be provided instead of the id and key values you have used.您可以定义必须提供这样一个表达式而不是您使用的idkey的方法。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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