在编译时 T 未知时如何声明 IQueryable<T>
How can I declare IQueryable<T> when T is unknown at compile time
我正在创建一个通用方法来调用存储库加载方法,以从 class T
定义的 table 中检索数据库记录,其中 T
直到运行次。
此外,下面的代码使用了已知类型 BLL.Entities.Unit,但我需要更改它以使用 GetData 方法中显示的模型类型。我不知道如何在不直接使用 Unit 的情况下格式化 param2 参数。
这是我方法中的代码:
public JsonResult GetData(string modelTypeString)
{
Type modelType = Type.GetType(modelTypeString);
MethodInfo generic = typeof(Repository).GetMethod("Load");
MethodInfo genericLoad = generic.MakeGenericMethod(modelType);
System.Linq.Expressions.Expression<System.Func<BLL.Entities.Unit, object>>[] param2 =
new System.Linq.Expressions.Expression<System.Func<BLL.Entities.Unit, object>>[1];
var returnObjects = genericLoad.Invoke(Repository, param2);
}
这是存储库加载方法:
public IQueryable<T> Load<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
{
IQueryable<T> query = entities.Set<T>();
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
}
return query;
}
此代码编译并执行,但我无法对 returnObjects
执行任何可查询的操作。我需要做类似的事情:
returnObjects.Select(u => new UnitViewModel
{
Id = u.Id,
Name = u.Name,
Description = u.Description,
DDLocationId = u.LocationId
})
.ToList();
使用您的存储库并使用 AutoMapper 映射所有对象不适合您吗?
你想要的是将你的 EntityFramework 对象变成 DTO。
我不知道有什么例外的自动映射器可以让你在没有任何 C# 反射的情况下做到这一点。
编辑:我认为您的问题应该是,如何将我的 EF 对象转换为 DTO。
我用一行代码解决了这个问题:
returnObjects.GetEnumerator();
这会强制从数据库中检索数据。之后,只需使用额外的反射代码来获取各个字段属性即可。
我正在创建一个通用方法来调用存储库加载方法,以从 class T
定义的 table 中检索数据库记录,其中 T
直到运行次。
此外,下面的代码使用了已知类型 BLL.Entities.Unit,但我需要更改它以使用 GetData 方法中显示的模型类型。我不知道如何在不直接使用 Unit 的情况下格式化 param2 参数。
这是我方法中的代码:
public JsonResult GetData(string modelTypeString)
{
Type modelType = Type.GetType(modelTypeString);
MethodInfo generic = typeof(Repository).GetMethod("Load");
MethodInfo genericLoad = generic.MakeGenericMethod(modelType);
System.Linq.Expressions.Expression<System.Func<BLL.Entities.Unit, object>>[] param2 =
new System.Linq.Expressions.Expression<System.Func<BLL.Entities.Unit, object>>[1];
var returnObjects = genericLoad.Invoke(Repository, param2);
}
这是存储库加载方法:
public IQueryable<T> Load<T>(params Expression<Func<T, object>>[] includeProperties) where T : class
{
IQueryable<T> query = entities.Set<T>();
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
}
return query;
}
此代码编译并执行,但我无法对 returnObjects
执行任何可查询的操作。我需要做类似的事情:
returnObjects.Select(u => new UnitViewModel
{
Id = u.Id,
Name = u.Name,
Description = u.Description,
DDLocationId = u.LocationId
})
.ToList();
使用您的存储库并使用 AutoMapper 映射所有对象不适合您吗?
你想要的是将你的 EntityFramework 对象变成 DTO。
我不知道有什么例外的自动映射器可以让你在没有任何 C# 反射的情况下做到这一点。
编辑:我认为您的问题应该是,如何将我的 EF 对象转换为 DTO。
我用一行代码解决了这个问题:
returnObjects.GetEnumerator();
这会强制从数据库中检索数据。之后,只需使用额外的反射代码来获取各个字段属性即可。