也许这个问题,总是在这个论坛上被问到,但我没有找到我需要的那个。我的问题是我有一个像这样的复合类
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);
}
}
并使用反射将其映射到客户类(对象),代码:
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);
}
有什么问题吗?请帮我。