locked
Linq to Sql dynamic RRS feed

  • Question

  • User-515183 posted

    I have dropdown that will have a text and a value which will be used as the tablename.

    How would I do a linq to Sql

    string TName = ViewBag.Name;

    var get = (from  p in db.[TName]  .Where etc

    Friday, February 17, 2017 7:13 PM

Answers

  • User1108898723 posted

    You can generate LINQ expression tree programmatically, but this is definitely not very elegant way of solving such simple task like that.

    Take a look to NReco.Data library, it can be used as alternative for dynamic LINQ-to-SQL queries:

    NReco.Data.DbDataAdapter dbAdapter;  // lets assume this is configured instance of the DbDataAdapter
    var q = new Query(TName);
    q.Condition = new QConditionNode( new QField(FldName), Conditions.Equal, new QConst(dropdownValue) );
    var queryResult = db.Select(q).ToRecordSet();

    Result can be mapped to annotated models, but since your table name is determined at runtime, it is more natural to use DataTable-like structure (RecordSet).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 19, 2017 4:19 PM

All replies

  • User1108898723 posted

    You can generate LINQ expression tree programmatically, but this is definitely not very elegant way of solving such simple task like that.

    Take a look to NReco.Data library, it can be used as alternative for dynamic LINQ-to-SQL queries:

    NReco.Data.DbDataAdapter dbAdapter;  // lets assume this is configured instance of the DbDataAdapter
    var q = new Query(TName);
    q.Condition = new QConditionNode( new QField(FldName), Conditions.Equal, new QConst(dropdownValue) );
    var queryResult = db.Select(q).ToRecordSet();

    Result can be mapped to annotated models, but since your table name is determined at runtime, it is more natural to use DataTable-like structure (RecordSet).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, February 19, 2017 4:19 PM
  • User1397563414 posted

    Hi sbuggle,

    You can use "switch" to differ different tables.

                string TName = ViewBag.Name;
                switch (TName) 
                {
                    case "people":
                    case "People":
                        var result = db.People.Where etc;
                        ......
                        break;
                    case "user":
                    case "User":
                        var result = db.Users.Where etc;
                        ......
                        break;
                    default:
                        etc;
                }

    Regards,
    JiyaoLee

    Monday, February 20, 2017 9:44 AM