也许这个问题,总是在这个论坛上被问到,但我找不到我需要的那个。 我的问题是我有一个像这样的复合类
class Customer
{
private int Id { set; get; }
private int Name { set; get; }
private Company Company { set; get; }
...
}
class Company
{
private int Id { set; get; }
private string Name { set; get; }
...
}
获取客户数据时
string sql = "SELECT cust.id, cust.name, comp.name AS [CompanyName] FROM Customer cust INNER JOIN Company comp ON cust.Company = comp.Id";
....
using (IDataReader dr = db.ExecuteReader(cmd))
{
if (dr.Read())
{
customer = (Customer)FillDataRecord(dr, customer);
}
}
并使用反射将其映射到Customer类(Object),代码为:
public static Object FillDataRecord(IDataRecord dr, Object obj)
{
try
{
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < dr.FieldCount; i++)
{
if (!dr[i].ToString().Equals(string.Empty))
{
type.GetProperty(dr.GetName(i)).SetValue(obj, dr[i], null);
}
}
return obj;
}
catch (Exception ex)
{
throw ex;
}
}
当它映射CompanyName时,它将返回错误“对象引用未设置为对象的实例”。我调试了,我知道这个问题,但直到现在,我无法解决它。
我知道AutoMapper或Dapper,但是当我申请这个案例时,我也遇到了同样的问题。
现在我正在使用ValueInjecter,从我所看到的它可以解决我的问题。 但我有cust.Id值与cust.Company.Id和cust.Name =“”和cust.Company.Name =“”
相同string sql = "select cust.id, cust.name, comp.name from customer cust inner join company comp on cust.company = comp.id";
while (dr.Read())
{
var cust = new Customer();
cust.InjectFrom<ReaderInjection>(dr);
cust.Company = new Company();
cust.Company.InjectFrom<ReaderInjection>(dr);
list.add(cust);
}
有什么不对吗?请帮帮我。
答案 0 :(得分:2)
你为什么使用Object?为什么不把它变成通用的?像这样:
public static T FillDataRecord<T>(IDataRecord dr) where T : new()
{
T returnedInstance = new T();
string fieldName = default(string);
try
{
PropertyInfo[] properties = typeof(T).GetProperties();
fieldName = dr.GetName(i);
foreach (PropertyInfo property in properties)
{
if (property.Name == fieldName)
{
// Handle the DBNull conversion issue..
if (dr.GetValue(i) == DBNull.Value)
property.SetValue(returnedInstance, null, null);
else
property.SetValue(returnedInstance, dr[i], null);
}
}
return returnedInstance;
}
catch (Exception ex)
{
// Handle exception here
}
}
然后你可以这样做:
Customer _customer = FillDataRecord<Customer>(dr);
或者,这个:
CustomerDetails _customerDetails = FillDataRecord<CustomerDetails>(dr);
回答你的问题..如果有可能从数据库中提取NULL ...你必须检查它。