I\'m using LINQ to SQL in C# in my application. I need to be able to select a column of a row, depending upon a variable. This is easy for the row as it\'s a simple where cl
Say the class that holds the permissions is named Permission
, you can define an extension method:
public static class PermissionExtensions
{
public static object SelectProperty(this Permission obj, string variable)
{
return obj.GetType().GetProperty(variable).GetValue(obj, null);
}
}
You can use this in your query like this:
(from s in dc.Permissions where s.dashboardname == permission select s)
.Single().SelectProperty(variable);
This doesn't select the property in the query but instead gets it from the instance.
Is it possible to change your database structure so that your columns becomes rows? (Pivot your table?)
Eg.
Permissions Table
-----------------
Id
Dashboardname
Page1
Page2
Page3
...
and turn it into
Permissions Table
-----------------
Id
Dashboardname
Pagename
Then you could use the where clause to select the row you want?
I'm not sure that I understand your question completely, so this might be a bit off. But could your problem perhaps be solved by using the LINQ Dynamic Query Library?
You can use the DynamicQuery library against any LINQ data provider (including LINQ to SQL, LINQ to Objects, LINQ to XML, LINQ to Entities, LINQ to SharePoint, LINQ to TerraServer, etc). Instead of using language operators or type-safe lambda extension methods to construct your LINQ queries, the dynamic query library provides you with string based extension methods that you can pass any string expression into.
See the above link for samples and downloads.
I don't think this is either possible or a good practice. Note that if the variable name is provided by user he or she can easily take all the data they want. Maybe you should try using enumeration and switch() clause?
Another answer that came in my mind is to create table with key-value pairs i.e.
where primary key is (dashboard, key)
.