简体   繁体   English

使用Entity Framework Core获取动态列

[英]Getting Dynamic Columns with Entity Framework Core

I am using a repository pattern that returns back IEnumerables with Entity Framework Core 2 and would like to implement a get method that takes a comma delimited string of column names and returns back a list of entities with only those columns. 我正在使用一个存储库模式,该存储库模式返回带有Entity Framework Core 2的IEnumerables,并且想要实现一个get方法,该方法采用以逗号分隔的列名字符串,并返回仅包含那些列的实体列表。 I want to limit the amount of data that comes from the DB (nice to have) but more importantly I need to limit the amount of data that goes from the REST api to the browser. 我想限制来自数据库的数据量(很不错),但更重要的是,我需要限制从REST api到浏览器的数据量。

It looks like the nuget package EntityFramework.DynamicLinq is the way to go. 看起来像nuget包EntityFramework.DynamicLinq是要走的路。 Best as I can tell from the documentation at Github Link . 我可以从Github Link的文档中得知。

I should be able to do this: 我应该能够做到这一点:

using EntityFramework.DynamicLinq

public class CompanyRepository
{
    public async Task<IEnumerable<Company>> Get(string columns)
    {
    return await _dbSet.AsNoTracking().Select("new(" + columns + ")").ToListAsync();
    }
}

Unfortunately that gives the following error for the Select call: 不幸的是,这给Select调用带来了以下错误:

The type arguments for method Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>) cannot be inferred from the usage 无法从用法推断方法Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)的类型参数

I figured it out. 我想到了。 I was importing the wrong namespace and the Select had to include the object type: 我导入了错误的名称空间,并且Select必须包含对象类型:

using System.Linq.Dynamic.Core;

public class CompanyRepository
{
    public async Task<IEnumerable<Company>> Get(string columns)
    {
    return await _dbSet.AsNoTracking().Select<Company>("new(" + columns + ")").ToListAsync();
    }
}

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

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