[英]Generics C# - Passing a Dynamic Type as an Argument
I ran into a small issue when trying to use SQL Queries with LinQ. 尝试在LinQ中使用SQL查询时遇到一个小问题。
The object I am receiving is as below: 我收到的对象如下:
public class Entity {
public int EntityId { get; set; }
public string TableName { get; set; }
}
Basically I need to run a script similar to this .. 基本上我需要运行与此类似的脚本。
var entityQuery = _context.Database.SqlQuery<T>("SELECT * FROM [dbo].[" + TableName + "] WHERE [Id]=" + EntityId).ToList();
Now the problem is that I can only know what type of object "T" is from the "TableName" property. 现在的问题是,我只能从“ TableName”属性中知道对象“ T”的类型。 How would I be able to instantiate the class in order to pass it instead of T?
我如何能够实例化该类以通过它而不是T?
Thanks :) 谢谢 :)
For those getting confused this is the method I am working on: 对于那些感到困惑的人,这是我正在研究的方法:
public void ModifyData(Entity item)
{
var table = item.TableName;
var id = item.EntityId;
var entityQuery = _context.Database.SqlQuery<T>("SELECT * FROM [dbo].[" + table + "] WHERE [Id]=" + id ).ToList();
//more code below;
}
Is there a different way to do this? 有其他方法可以做到这一点吗?
Why do you want to pass a tableName ? 为什么要传递tableName? and too in a "int tableName" ?
也是在“ int tableName”? Why dont use the entity type passed in ?
为什么不使用传入的实体类型? Well anyways, you can try something like this:
好吧,无论如何,您可以尝试这样的事情:
static string Data(string tableName, string columnNames, string orderBy)
{
var type = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(i => i.Name == tableName);
using (var context = new BloggingEntities())
{
var data = Select(type, columnNames, orderBy, context);
var str = JsonConvert.SerializeObject(data);
return str;
}
}
static string Select(Type type, string columnNames, string orderBy, BloggingEntities _dbContext)
{
var data = _dbContext.Set(type).AsNoTracking().AsQueryable();
var selectStatement = "new ( " + columnNames + ")";
var filtered = data.Select(selectStatement).OrderBy(orderBy);
return JsonConvert.SerializeObject(filtered);
}
Note: You may have to install this : Install-Package System.Linq.Dynamic
注意:您可能必须安装:
Install-Package System.Linq.Dynamic
In your case you can directly use 您可以直接使用
var data = _dbContext.Set(type).AsNoTracking().AsQueryable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.