问题描述
我正在尝试使用 Dapper 和存储过程编写一些更通用的代码。我做了一些研究,但我在这部分卡住了..
我有一些类的行为类似于某些存储过程将返回的实体(这些过程无法修改)。
例如,我有这两个类:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
存储过程通常返回一些select子句,在这个例子中它返回两个select子句,每个用于用户和角色的信息,所以我有以下类来存储它们..
public class UserAndRoleInfo
{
public IEnumerable<User> users { get; set; }
public IEnumerable<Role> roles { get; set;}
}
在这个项目中,我们必须使用 Dapper,所以我正在做一个泛型函数,其中 T 是将要返回的类,这个类具有与上图相同的结构,并且可以有两个或多个实体作为属性。
主要思想是获取T的属性,然后为每个属性获取select子句的返回值cast为属性类型,最后将该属性添加到将要返回的类实例中。
public async Task<T> ExecuteStoredProcedureMultiQuery<T>(string cnx,string storedProcedure,object param = null) where T : class,new()
{
using (var conn = new sqlConnection(cnx))
{
conn.open();
var result = param == null
? await conn.QueryMultipleAsync(
storedProcedure,commandType: CommandType.StoredProcedure
).ConfigureAwait(false)
: await conn.QueryMultipleAsync(
storedProcedure,param: param,commandType: CommandType.StoredProcedure
).ConfigureAwait(false);
T res = new T();
Type t = typeof(T);
PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(PropertyInfo propInfo in propInfos)
{
// I want to do something like this
propInfo.PropertyType propValue = result.Read<propInfo.PropertyType.GetEnumUnderlyingType()>();
propInfo.SetValue(res,propValue);
}
conn.Close();
conn.dispose();
return res;
}
}
这里的问题是我不知道如何获得这个
propInfo.PropertyType propValue = result.Read<propInfo.PropertyType.GetEnumUnderlyingType()>();
我正在使用 Activator.CreateInstance(propInfo.PropertyType)
,但我不确定在这种情况下如何实现它。
如果有什么不清楚或需要更多信息,我会在这里回答。提前致谢。
解决方法
使用答案 here 作为参考,您可以这样做:
foreach (var propInfo in propInfos)
{
var method = result.GetType().GetMethod(nameof(result.Read));
var generic = method.MakeGenericMethod(propInfo.PropertyType.GetEnumUnderlyingType());
var propValue = generic.Invoke(result,null);
propInfo.SetValue(res,propValue);
}