1

I have an requirement to get the records from table. I want to fetch data column from DB based on condition.

Suppose I have a grid which equally represents the table in database. This grid have a checkbox in header within each heading.

If checkbox corresponding to UserId is checked, I have to get "UserId" column like this

1  
2  

If user has also checked Name with it, now my list should also contain name with it like:

1     First    
2     Second   

and if the user clicks address also, I have to get address also.

The table/Grid is here:

UserId    Name      Address
----------------------------
  1       First     America  
  2       Second    France

I tried with the following query but confused how can I concatenate more search columns with in single query like::

var ll = DB.Users.Select(d => d.Name).ToList();

Now, I have to introduce one more column in the above query. How can I do it?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sweetie
  • 1,298
  • 6
  • 24
  • 48
  • You could use dynamic expression builder like described here: http://stackoverflow.com/a/16517768/335784 – Ben Feb 26 '14 at 19:55

1 Answers1

0

Make a separate LINQ query for each column combination, or try using a stored procedure which will solve this problem.

Using raw SQL you could build a dynamic query which would return different columns based on the checkbox parameters.

EDIT: Since you want to use LINQ only, I suggest you return all possible columns and filter the unwanted columns out at the presentation part of the application.

Howie
  • 2,760
  • 6
  • 32
  • 60
  • Sir, I do not want to use Store Procedure. I have to do in Linq only. I just have a option to create if and else conditions only. if(name is not empty{I will write query to get name }else{name and Id , I will write query getting records with name and Id} and so on but this will create many if else conditions in my page. It is okay for 3 coloums but what If I have 20 coloums of table. It does not makes any sense. I have to get it within same query is my requirement.Please help me. – Sweetie Feb 27 '14 at 05:12
  • I don't see that being possible in a LINQ query as you cannot (simply) dynamically build the query in runtime. You could simply return all columns and filter after. – Howie Feb 27 '14 at 07:22