LINQ Select from dynamic tableName string

后端 未结 2 1861
忘掉有多难
忘掉有多难 2020-12-04 00:05

I want to get list of records from an entity model (I\'m using EF version 5) with a particular accountID. I\'m being supplied with the tableName string (this has to be dynam

2条回答
  •  [愿得一人]
    2020-12-04 01:01

    The var query = table.Where(....).Select(...) is the correct move as it allows reflection for the query builder at runtime. However, t.AccountID is an error because of the type of t remains unknown.

    I've previously used a similar approach in LINQ to SQL, using System.Linq.Expressions.Expression, e.g.:

        // NOT TESTED
        var table=context.GetTable(dynamicTableName);
        var theT=table.Experssion; // actually, I forget. DynamicExpression  or MemberBinding? or
        var theField=Expression.Field(theT, "AccountID"); // or dynamic name
        var query=table.Where(Expression.Equal(theField, accID);
        var recList=query.ToList();
    
    
    

    If your object has a common interface there is a simpler syntax:

    IQueryable table = context.GetTable("table") as IQueryable;
        var recList=from r in table
                    where table.AccountID == ac // if your AccountID is on MyInterface
                    select table;
    

    If you only have a few tables to support, you could do this as well:

        IQueryable table;
        if("table1"==tableName)
           table=_db.table1
        elseif("table2"==tableName)
           table=_db.table2
        elseif("table3"==tableName)
           table=_db.table3
        else
           throw exception
    

    提交回复
    热议问题