0

I have a requirement to showing all or less properties of an entity in the grid based on the page mode user select. For example I have three page modes

Minimal (will show 8 properties of an entity in the grid)

Standard (will show 12 properties of an entity in the grid)

Extended (will show 15 properties of an entity in the grid)

How can I make Select predicate dynamic to include the specified no of columns of an entity based on user page mode. Lets say I have Entity company with 15 properties I want to do something like this

dbContext.Companies.Select([predicate for choosing different no of columns?])
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
Waqas Anwar
  • 350
  • 5
  • 15

1 Answers1

3

You cannot solve this using Predicates, because they always return bool.

What you need is a function expression that takes a Company object as a parameter and returns an object. Concretely, you need an Expression<Func<Company, object>>.

This is how you can define the three types of selection:

Expression<Func<Company, object>> minimal = e => new { e.Prop1, ..., e.Prop8 };
Expression<Func<Company, object>> standard = e => new { e.Prop1, ..., e.Prop12 };
Expression<Func<Company, object>> extended = e => new { e.Prop1, ..., e.Prop15 };

and then use them as you wish:

dbContext.Companies.Select(minimal);
// or
dbContext.Companies.Select(standard);
// or
dbContext.Companies.Select(extended);
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137
  • Thanks wolf for this solution but I have a question here. I have an admin section where admin select which properties/columns to show on the main page. So I am getting a string array of 8, 12 or 15 columns how I will add those columns in the above solution. – Waqas Anwar Feb 14 '13 at 07:51
  • @Waqas I've attempted to do this in several ways, but haven't succeeded so far. I think the solution would be to build an expression that populates a dynamic object with the entity's properties, but don't know how to do it or if it's even possible. [This answer](http://stackoverflow.com/a/3591820/390819) gave me hope, but I still need to dig further. – Cristian Lupascu Feb 14 '13 at 09:17
  • Thanks @wolf, I also find this link may be it helps you too. http://www.albahari.com/nutshell/predicatebuilder.aspx – Waqas Anwar Feb 14 '13 at 09:44
  • @Waqas Nice link, but I think it's only about building predicates (functions that return bool and can be used in LINQ filters). I don't know if it helps with building the `select` list. – Cristian Lupascu Feb 14 '13 at 10:14