Dan*_*ase 1 .net c# reflection ado.net sqlclient
我试图想出一种方法,只是将SQL Server中的表加载到一个类中,而不必告诉它任何东西.基本上,只需创建类并让它知道要加载什么,基于此.这是我到目前为止所拥有的.
我的问题是,是否有一些方法可以避免硬编码类型,调用reader.readString,reader.readInt32等.基于FieldType?
private Int32? readInt32(SqlDataReader reader, string columnName)
{
Int32? result = null;
if (!reader.IsDBNull(reader.GetOrdinal(columnName)))
{
result = reader.GetInt32(reader.GetOrdinal(columnName));
};
return result;
}
public List<T> readTable(string table, string wherecls, string connStr)
{
List<T> result = new List<T>();
using (SqlConnection connection = new SqlConnection(connStr))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from " + table;
if (wherecls.Length > 0) command.CommandText += " where " + wherecls;
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Object i = Activator.CreateInstance(typeof(T));
System.Reflection.FieldInfo[] fieldInfoList = typeof(T).GetFields();
foreach (System.Reflection.FieldInfo f in fieldInfoList)
{
if (f.FieldType == typeof(string)) f.SetValue(i, readString(reader, f.Name));
if (f.FieldType == typeof(Int32)) f.SetValue(i, readInt32(reader, f.Name));
if (f.FieldType == typeof(Int16)) f.SetValue(i, readInt16(reader, f.Name));
if (f.FieldType == typeof(byte)) f.SetValue(i, readByte(reader, f.Name));
if (f.FieldType == typeof(short)) f.SetValue(i, readShort(reader, f.Name));
}
result.Add((T)i);
}
}
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
谢谢Dan Chase
你所描述的是很多工作......而且正是像"小精灵" 这样的工具已经做了.所以我的建议在这里:使用小巧玲珑:
// Dapper adds a Query<T>(this DbConnection, ...) extension method
var data = connection.Query<T>(sql, args).AsList();
Run Code Online (Sandbox Code Playgroud)
但是,我会说让string wherecls我的脊椎发抖 - 这听起来像是一个SQL注入的噩梦.但是......这取决于你.
| 归档时间: |
|
| 查看次数: |
461 次 |
| 最近记录: |