user1453999
user1453999

Reputation: 120

How do I create a linq query where the select column name is a variable

I have a configuration table that contains various configurations for permissions to show various data a e.g.

PermissionTable
key1    key2    showconfig1 showconfig2
1       A            Y             N
2       B            N             N
3       C            Y             Y

An application of various webservices make queries at different points in the code to the same table to get values from different showconfig columns for permissions.
How can I create a generic centralized query where the app can pass the key1 value , the key2value and a columnName variable to get the value of a particular column row without having to write a separate query to query each column row or without having to write a query to retrieve all the columns values for a particular row?

e.g. the following just returns the column name I want the value in that column:

public string GetPermission(int key1, int key2 ,string columnName)
{
   string show = "N";  
   var show = (from p in db.PermissionTable
               where p.key1== key1
               && p.key2 == key2
               select p.[columnName]).FirstOrDefault().ToString();
   return show;
}

Upvotes: 0

Views: 5056

Answers (2)

stepandohnal
stepandohnal

Reputation: 457

You can use dynamic linq extensions see http://dynamiclinq.codeplex.com/documentation

With this library you can select the data in format like this:

db.PermissionTable.Select("MyColumn");

Upvotes: 1

andleer
andleer

Reputation: 22568

You can dynamically apply filters to your query but it is not easy to dynamically generate or vary your result types based on some type of condition. Types (anonymous or otherwise) are defined at compile time, not runtime.

var result = from p in db.PermissionTable
          select new { p.ColumnName, p.Key1, p.Key2 };

if(condition1)
    result = result.Where(i => i.Key1 == filter1);

if(condition2)
    result = result.Where(i => i.Key2 > 0);

var result2 = from p in result
    select p.ColumnName;

return result2.FirstOrDefault().ToString();

If you really need to vary the query columns based on different criteria, I think it is reasonable to have multiple queries.

Upvotes: 1

Related Questions