Select column based on variable in LINQ to SQL

前端 未结 5 1520
眼角桃花
眼角桃花 2021-01-19 03:43

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

相关标签:
5条回答
  • 2021-01-19 04:34

    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.

    0 讨论(0)
  • 2021-01-19 04:36

    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?

    0 讨论(0)
  • 2021-01-19 04:40

    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.

    0 讨论(0)
  • 2021-01-19 04:44

    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?

    0 讨论(0)
  • 2021-01-19 04:44

    Another answer that came in my mind is to create table with key-value pairs i.e.

    • dashboard
    • key
    • value

    where primary key is (dashboard, key).

    0 讨论(0)
提交回复
热议问题