如何在SqlDataReader上下文中使用属性?
问题描述:
我试图建立一个通用的SQL执行器。如何在SqlDataReader上下文中使用属性?
它的工作,如果我的DTO类属性具有相同的名称比我的SQL表列。
为了增加我的代码的泛型部分,我添加了一个属性到我的DTO中,以便将我的DTO属性分隔到SQL列。
但它不工作
我的DTO类:
public class CarModels
{
[DbColumn("ca_id")] //column name
public string Id { get; set; }
[DbColumn("ca_label")] //column name
public string Label { get; set; }
}
我的泛型方法:
public List<T> ExecuteSQLSELECTCommand<T>(string SQLcommand) where T : new()
{
IDictionary<string, string> databaseMappings = new Dictionary<string, string>(); ;
Get_Connection();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = string.Format(SQLcommand);
List<T> res = new List<T>();
try
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
T t = new T();
for (int inc = 0; inc < reader.FieldCount; inc++)
{
Type type = t.GetType();
//how to get attribute link to current FiedCount ?
PropertyInfo prop = type.GetProperty(reader.GetName(inc));
prop.SetValue(t, reader.GetValue(inc), null);
}
res.Add(t);
}
reader.Close();
}
catch (Exception e)
{
}
return res;
}
}
和我的电话:
List<CarModels> carTest = db.ExecuteSQLCommand<CarModels>("SELECT ca_id, ca_label from cartracker.ca_cars");
我的问题,怎么能我恢复了att的价值ribute为了在MySqlDataReader上下文中构建一个PropertyInfo?
谢谢。
答
你可以使用这样的一个类。你能告诉我,如果有帮助:
public class AnEntity<T> where T : class, new()
{
public T AnEntity(string[] token, ref int i, out TokenEnum tokenEnum,
out string tokenException)
{
...
PropertyInfo[] properties = typeof(T).GetProperties();
try
{
foreach (PropertyInfo property in properties)
{
...
if (property.Name == "AName")
{
break;
}
...