I'm trying to do some code more generic with Dapper and stored procedures. I've made some research, but I got stuck on this part..
I have some classes that act like entities that will be returned by some stored procedures (those procedures can't be modified).
For example, I have these two classes:
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; }
}
The stored procedures usually return some select clauses, for this example it returns two select clauses, each for User and Role's information, so I have the following class to store those..
public class UserAndRoleInfo
{
public IEnumerable<User> users { get; set; }
public IEnumerable<Role> roles { get; set;}
}
In this project we have to use Dapper, so I'm doing a generic function where T is the class that will be returned, this class has the same structure as shown above and could have two or more entities as attributes.
The main idea is to get the properties of T, then for each property get the value returned by the select clause cast as property type, and finally add this property to the class instance which will be returned.
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;
}
}
The problem here is that I'm not sure how to get this
propInfo.PropertyType propValue = result.Read<propInfo.PropertyType.GetEnumUnderlyingType()>();
I was working around with Activator.CreateInstance(propInfo.PropertyType)
, but I'm not sure how to implement it in this case.
If something is unclear or more information is needed, I'm here to answer. Thanks in advance.