简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM