我正在尝试编写动态选择语句。我有以下几点:
public class MainList
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
public string Prop3{ get; set; }
}
public class SearchObject
{
public string Prop1{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想构建如下表达式
var newList = MainList.Select(n => new SearchObject { Prop1 = n.Prop1});
Run Code Online (Sandbox Code Playgroud)
我使用的代码基于MainList创建一个列表。然后,我现在通过传递SearchObject类型和我想填充的参数来创建选择表达式。它一直运行到倒数第二行。
public void Start()
{
List<MainList> newList = new List<MainList>(); //This has a ton list objects
var result = newList.Select(CreateSelect<SearchObject>("Prop1"));
}
public static Func<MainList, T> CreateSelect<T>(string fields)
{
var par = Expression.Parameter(typeof(T), "n"); …Run Code Online (Sandbox Code Playgroud) 我传递了一个我要查询的实体类型名称的字符串,并根据字符串获取类型.我想得到DbSet回来并返回IQueryable.问题出在我正在做的事情(DbSet<tableEntity>)并收到以下错误:
tableEntity是一个变量,但像类型一样使用
当试图施放.有办法解决这个问题吗?
public object GetList(string tableEntity)
{
Type tableEntity = Type.GetType("TestProject." + typeName + ", TestProject");
var dbObject = (DbSet<tableEntity>)typeof(DbContext).GetMethod("Set", Type.EmptyTypes)
.MakeGenericMethod(tableEntity)
.Invoke(databaseContext, null);
return dbObject.AsQueryable();
}
Run Code Online (Sandbox Code Playgroud)
编辑
只是要添加我无法访问我们通过字符串传递名称的类型.