3

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

6
  • If you really need to return a dynamic subset of the columns in your API, I would still select them all from the DB and use some code (probably just if/else statements) to map the columns you want to the object you are returning from the API. Commented Jul 7, 2016 at 14:28
  • I just saw your older question. I'd advise you not to build dynamic queries to populate drop downs. Just create a specific endpoint for each type of data you need. AccountID/Name only vs all account details. Commented Jul 7, 2016 at 14:34
  • @Ryan that's what I was thinking, creating a separate endpoint for these. I was just thinking about going the dynamic route for future proofing if I need to get specific fields later. Commented Jul 7, 2016 at 14:40
  • Are you sure you need Reflection? It seems that you can do this with Expressions (see Expression.MakeMemberAccess and the like) Commented Jul 8, 2016 at 11:24
  • For situations like this, you can build a sql and execute it through the context.Database. using (var context = new myContext()) { result = context.Database.SqlQuery<T>(sql).ToList(); } Commented Jul 8, 2016 at 14:53

1 Answer 1

1

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;
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.