using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace 异步Test
{
public class SqlHelper
{
public void Test()
{
using (SqlConnection con = new SqlConnection())
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "";
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var result= MapEntity<Person>(reader);
}
}
}
}
}
}
private TResult MapEntity<TResult>(SqlDataReader reader) where TResult : new()
{
var properites = typeof(Person).GetProperties();
var result = new TResult();
foreach (var item in properites)
{
var index = reader.GetOrdinal(item.Name);
var data = reader.GetValue(index);
//item.SetValue(person, data);
item.SetValue(result, Convert.ChangeType(data, item.PropertyType));
}
return result;
}
}
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
}
}