Getting Dynamic Columns with Entity Framework Core

c# entity-framework-core linq

Question

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. 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.

It looks like the nuget package EntityFramework.DynamicLinq is the way to go. Best as I can tell from the documentation at 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:

The type arguments for method Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>) cannot be inferred from the usage

1
0
2/5/2018 2:24:31 AM

Accepted Answer

I figured it out. I was importing the wrong namespace and the Select had to include the object type:

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();
    }
}
2
2/5/2018 5:56:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow