c# - 在 EF Core 中创建外键的通用获取

标签 c# entity-framework-core .net-6.0 ef-core-6.0

我有这个功能

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

但是它仅在使用客户端评估时有效,而且我担心性能,因为这将是一个非常核心的功能。是否可以做同样的事情,但让它在服务器上评估,或者至少提高性能?

最佳答案

Queryable.Where() 方法需要 Expression<Func<TSource,bool>>表达式,用于“评估”应用于 Set<T> 时应返回哪些实体。实例。您可以定义您的方法,必须提供这样的表达式而不是 idkey您使用过的值。该方法可以如下所示:

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

然后你像这样使用它:

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

关于c# - 在 EF Core 中创建外键的通用获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73602325/

相关文章:

c# - 如何将 byte 解释为 int?

c# - ExecuteScalar 为 SQL count(*) 返回 false

.net-core - EF Core 在迁移过程中锁定数据库

c# - 为什么 services.AddDbContext<dbContext>() 使 dbContext 成为 Scoped 服务?不应该是单例服务吗?

c# - 如何将单个 Controller 与不同的 DBContext 一起使用?

azure-devops - 在 Azure 构建代理上构建时,找不到 ASP.NET Core 6 MVC 应用程序的错误 View Index.cshtml

c# - 如何从字节数组中删除空值?

c# - 在不删除数据的情况下重命名 Entity Framework Core 中的外键

azure-active-directory - 使用 Azure Active Directory 作为 Identity Server 的外部登录

c# - 没有参数的 F# 类构造函数 --- 使用 f# 的 filehelpers 时出错