LINQ Select from dynamic tableName string

后端 未结 2 1852
忘掉有多难
忘掉有多难 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 00:52

    I built a DynamicRepository for a project I am working on. It uses generic methods exposed through EF along with dynamic linq. It might be helpful to look at that source code here:

    https://dynamicmvc.codeplex.com/SourceControl/latest#DynamicMVC/DynamicMVC/Data/DynamicRepository.cs

    You can query the entity framework metadata workspace to get the type for a given table name. This link might help: Get Tables and Relationships

    0 讨论(0)
  • 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<object>();
    

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

    IQueryable<MyInterface> table = context.GetTable("table") as IQueryable<MyInterface>;
        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<MyInterface> table;
        if("table1"==tableName)
           table=_db.table1
        elseif("table2"==tableName)
           table=_db.table2
        elseif("table3"==tableName)
           table=_db.table3
        else
           throw exception
    
    0 讨论(0)
提交回复
热议问题