Selecting specific columns with Linq, using string or propertyInfo

.net c# entity-framework entity-framework-6 linq

Question

I am rebuilding our reporting system using EF, where as our old system used a lot of dynamic SQL (bad i know), so i would like to do it using Linq, so it uses parameterized queries etc.

In a report a user can choose which columns of data they want to view. Now how can i take these values and return an SQL statement using Linq and get the columns i need? I wonder if i should even bother and just return all the data, then just show the columns the user wants on screen, which may be want i need to do, but thought i would ask anyway.

So lets take the following Linq example, i say i would only like the Id, Name and Town, how could i do this. Currently i have something similar to

var columns = new List<string>() { "Id", "Name", "Town" };

return _context.Data
    .Where(e => e.Name == "test")
    .ToList();

Is this even possible?

1
0
2/25/2015 9:36:48 AM

Popular Answer

if you yant select propertys accordance their names try Dynamic LINQ library:

public List<Data> ListByNames(string[] arr)
{
    var str = string.Format("new ({0})", string.Join(", ", arr));
    return _context.Data.Select(str);
}

Or write your own Expression, see @TomBrothers answer: https://stackoverflow.com/a/4546633/1271037

1
5/23/2017 11:43:25 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