Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using Entity Framework 6 with ASP.Net MVC 5. When using a database context object, is there a way to use a variable for the table name, without having to manually write the query?

For example:

var tableName = "NameOfTable";

result = context.tableName.Find(...);

I know that particular code won't work, because tableName is not defined in context, but is there a way to achieve the desired effect?

There are some similar questions on this site, but they never really solved the problem and they were for earlier versions of entity framework, so I'm hoping that there is an answer now.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
997 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a simple solution using a switch to associate a particular Type to a table. You could also maintain use some sort of Dictionary<string, Type> object.

var tableName = "Table1";
// Get proper return type.
Type returnType;
switch(tableName) {
    case "Table1":
        returnType = typeof(Table1EntityType);
        break;
    case "Table2":
        returnType = typeof(Table2EntityType);
        break;
}
var query = context.Set(returnType);
// Filter against "query" variable below...
var result = query.Where(...);

-or-

var tableName = "Table1";
Dictionary<string, Type> tableTypeDict = new Dictionary<string, Type>()
{
    { "Table1", Table1Type },
    { "Table2", Table2Type }
}; 
var query = context.Set(tableTypeDict[tableName]);
// Filter against "query" variable below...
var result = query.Where(...);

EDIT: Modified for Entity Framework

EDIT2: Use typeof per @thepirat000 's suggestion


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...