Dynamic table name in linq
In your DbContext class, add a method say called Set that returns:
public DbSet Set(string name)
{
// you may need to fill in the namespace of your context
return base.Set(Type.GetType(name));
}
Which you can query like this:
using (var db = new YourDataContext())
{
// Since your DbSet isn't generic, you can can't use this:
// db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
// Your queries should also be string based.
// Use the System.Linq.Dynamic nuget package/namespace
var results = db.Set("Namespace.EntityName")
.AsQueryable()
.Where("SomeProperty > @1 and SomeThing < @2", aValue, anotherValue);
// you can now iterate over the results collection of objects
}
More information on System.Linq.Dynamic can be found here
LINQ Select from dynamic tableName string
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
Dynamic Table Names in Linq to SQL
You can call the ExecuteQuery method on the DataContext instance. You will want to call the overload that takes a Type instance, outlined here:
http://msdn.microsoft.com/en-us/library/bb534292.aspx
Assuming that you have a type that is attributed correctly for the table, passing that Type instance for that type and the SQL will give you what you want.
dynamic table name in Entity
Your question isn't very clear, but if you mean that You wanna do it in a generic way, then yes that is possible. You can take advantage of the Set<T>
method. For example:
public void LoadToGrid<T>(GridType grid) where T: class, new() {
grid.DataSource = dbContext.Set<T>().ToList();
}
And to customize the data fields in your grid, your can add this overload
public void LoadToGrid<T>(GridType grid, Expression<Func<T,Object>> selectExpression) where T: class, new() {
grid.DataSource = dbContext.Set<T>().Select(selectExpression).ToList();
}
Dynamic table names in Entity Framework linq
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
Related Topics
Reading Fromuri and Frombody at the Same Time
Httpwebrequest Times Out on Second Call
Improving/Fixing a Regex for C Style Block Comments
Client Id for Property (ASP.NET MVC)
"Nested Foreach" VS "Lambda/Linq Query" Performance(Linq-To-Objects)
Dynamically Create a Generic Type for Template
How to Get Dpi Scale for All Screens
Image.Fromstream() Method Returns Invalid Argument Exception
Convert String to Brushes/Brush Color Name in C#
Internal .Net Framework Data Provider Error 1025
How to Perform a Circular Bit Shift in C#
Monitor Process Start in the System
Error "This Stream Does Not Support Seek Operations" in C#