Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework get specific column from a string

I have a Web API project that uses Entity Framework. I have an action api/account that given an ID returns that account.

There is an additional parameter that can be provided which is what fields to be returned e.g. api/account?field=name

I'm trying to work out the best way of translating from this string input to Entity Framework. I know I can use .Select() to only get certain columns but that takes in a Func and the only way I can think of getting from the string to a Func is by using Reflection. This seems like it will be a peformance hit if I have to do Reflection for every property passed in, is there a better way of doing this?

Thanks

like image 617
ADringer Avatar asked May 12 '26 19:05

ADringer


1 Answers

You can use this library System.Linq.Dynamic from Nuget, and this query

var selectStatement = string.Format("new ({0},{1})", field1, field2);
var result = db.Users.Select(selectStatement).ToListAsync().Result;
like image 103
Mohammad Akbari Avatar answered May 14 '26 09:05

Mohammad Akbari