LINQ to Entities select columns with expression parameter

帅比萌擦擦* 提交于 2020-01-13 05:18:06

问题


I cannot wrap my head around how i manage to select columns in a queryable by specifying an expression as a parameter.

Method A(IQueryable<Order> query)

Inside Method A i want to specify which columns to select, so i dont get all columns right away, like this:

query.Select(x => new { x.OrderNumber, x.Payment, x.Customer })

This is easy if i specify this directly in Method A, but i want to pass the information using a parameter. I tried using a expression like this:

Expression<Func<Order, dynamic>> columns

But i can't get it to work, since i can only specify one columns, where i call Method A, like this:

MethodA(query, (x) => x.OrderNumber);

How can i specify more than one property?


回答1:


I found the solution. I simply had to specify an anonymous type like this:

MethodA(query, order => new { order.OrderNumber, order.Payment })

Now i can pass in my Select expression from other methods.




回答2:


If you just want to pass in column names, why not pass strings as an array?

void MethodA(params string[] columns)



来源:https://stackoverflow.com/questions/44241996/linq-to-entities-select-columns-with-expression-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!