I need to retrieve user defined columns from database with Entity Framework. I need to create column Projection based on passed collection, a List of strings, where each element contains column names, with Entity Framework
I have a list of string which contains strings like this;
List<string> columnsToSelect = new List<string>();
columnsToSelect.Add("col1 + col2");
columnsToSelect.Add("col2");
columnsToSelect.Add("col3 + col4");
I have a table called 'RawData' with 6 columns like this:
Id EmpId col1 col2 col3 col4
Now, if i were to query simple
var rawDatacolums = Context.RawData.where(a => a.EmpId = @EmpId)
this will generate SQL statement like this,
Select Id,EmpId,col1,col2,col3,col4 from RawData
where EmpId = @EmpId
Here i want to pass columnsToSelect as argument and my result should be based on column selector i am passing in List
What i want to do is,
var rawDatacolums = Context.RawData.select(columnsToSelect).where(a =>
a.EmpId = @EmpId)
Which should generate SQL like;
Select col1 + col2 as Col1Col2, col2 as Col2, col3 + col4 as Col3Col4
from RawData where EmpId = @EmpId
I have tried to use "SelectProperties" from this article here:
https://byalexblog.net/entity-framework-dynamic-columns https://github.com/lAnubisl/entity-framework-dynamic-queries/blob/master/entity-framework-dynamic-queries/SelectiveQuery.cs
var rawDatacolums = Context.RawData.SelectProperties(columnsToSelect)
if a pass exact columns like col1, col2 as list it works but it doesn't work the way i want for example Sum of Two columns
My Requirement is i need to project addition of columns like 'col1 + col2' & 'col3 + col4'
Updated Answer
Based on couple of suggestions, i played more with Dynamic LINQ and i made it work, i was able to apply various math conditions on my projection and was able to create Dynamic Class out of it
The original github reference is as below: https://github.com/kahanu/System.Linq.Dynamic
but i found explanation here more useful please take a look here: http://ak-dynamic-linq.azurewebsites.net/GettingStarted#conversions
Some other material i referred and had to use - which maybe helpful to someone is here - http://www.albahari.com/nutshell/predicatebuilder.aspx
Sample working code would look like this;
var sampleQuery = "New(Col1+Col2 as Stage1Count)";
IEnumerable queryResult= Context.RawData.AsQueryable().Select(sampleQuery );
System.Diagnostics.Debug.WriteLine("Debug Sample Query: " + queryResult.ToString());
foreach (var cust in queryResult)
{
System.Diagnostics.Debug.WriteLine("Debug Sample StageCount : " + cust.ToString());
}
Thanks all for your comments and suggestions! Cheers!