我试图想出一种方法,将表从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;
}
谢谢 丹·蔡斯
你描述的是很多工作...这正是像"dapper"这样的工具已经做到的。所以我在这里的建议:使用dapper:
// Dapper adds a Query<T>(this DbConnection, ...) extension method
var data = connection.Query<T>(sql, args).AsList();
然而,我会说string wherecls
让我的脊椎发抖 - 这听起来像是SQL注入的噩梦。但。。。这取决于你。
试试这个。
确保类型具有公共默认构造函数(不带参数(,并且 SQL 字符串中的列名与类型的公共属性的名称完全匹配。
namespace MyNamespace {
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
public static class MyExtensions {
public static IEnumerable<T> Query<T>(this SqlConnection cn, string sql) {
Type TypeT = typeof(T);
ConstructorInfo ctor = TypeT.GetConstructor(Type.EmptyTypes);
if (ctor == null) {
throw new InvalidOperationException($"Type {TypeT.Name} does not have a default constructor.");
}
using (SqlCommand cmd = new SqlCommand(sql, cn)) {
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
T newInst = (T)ctor.Invoke(null);
for (int i = 0; i < reader.FieldCount; i++) {
string propName = reader.GetName(i);
PropertyInfo propInfo = TypeT.GetProperty(propName);
if (propInfo != null) {
object value = reader.GetValue(i);
if (value == DBNull.Value) {
propInfo.SetValue(newInst, null);
} else {
propInfo.SetValue(newInst, value);
}
}
}
yield return newInst;
}
}
}
}
}
}
也许我的解决方案更好一点。我使用扩展填充类型 T,并按照我喜欢的顺序处理空值和填充属性。
例:
public async Task<ObservableCollection<T>> Search_data<T>()
{
var data = new ObservableCollection<T>();
try
{
using (OracleConnection con = new OracleConnection(connn_string))
{
con.Open();
OracleCommand cmd = new OracleCommand("MySchema.SomeTable", con)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.Add("result", OracleDbType.RefCursor, ParameterDirection.Output);
using (OracleDataReader rdr = cmd.ExecuteReader())
{
while (await rdr.ReadAsync())
{
var item = Activator.CreateInstance<T>();
item.SetValue("NAME", rdr.IsDBNull(0) ? null : rdr.GetString(0));
item.SetValue("SURNAME", rdr.IsDBNull(1) ? null : rdr.GetString(1));
item.SetValue("ADDRESS", rdr.IsDBNull(2) ? null : rdr.GetString(2));
data.Add(item);
};
}
}
return data;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
外延:
public static void SetValue<T>(this T _source, string _property_name, object _value)
{
_source.GetType().GetProperty(_property_name).SetValue(_source, _value);
}