0

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

4
  • TRY THIS. public async Task<IEnumerable<Company>> Get(string columns) { return await _dbSet.AsNoTracking().Select<IEnumerable<Company>>("new(" + columns + ")").ToListAsync(); } Commented Feb 5, 2018 at 2:27
  • @GaurangDave That lines gives the following error: 'IQueryable<Company>' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'IQueryable<Company>' could be found Commented Feb 5, 2018 at 4:28
  • This is one of the function I have with dynamic columns. You can avoid use of "Id" if not useful to you. Else this function returns the value of dynamic column. You can modify it as per your need and let me know. public int GetIntVal(string ColumnName, int Id) { var repo = repo.Entities.Where(x => x.ID == Id).Select(e => e).FirstOrDefault(); if (repo == null) return 0; var value = repo.GetType().GetProperties().Where(a => a.Name == ColumnName).Select(p => p.GetValue(repo, null)).FirstOrDefault(); return value != null ? Convert.ToInt32(value.ToString()) : 0; } Commented Feb 5, 2018 at 5:29
  • @GaurangDave. Thanks for the help. I figured it out. I'll posted it as an answer Commented Feb 5, 2018 at 5:53

1 Answer 1

2

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.