我正在使用AutoMapper使用代码,如下所述 http://elegantcode.com/2009/10/16/mapping-from-idatareaderidatarecord-with-automapper/
我觉得它很脆弱......而且不可预测.
1)具有相同datareader的相同代码有时会将值返回到dto结果集,有时则不会.2)我有一个来自数据库的ID值为100,200.当它映射到整数类型的DTO时,这个100被改为一个大值(如234343211).
关于为什么我看到这种不一致的任何想法.我应该使用标准吗(reader.Read())?并停止使用automapper?
小智 18
我遇到了同样的问题.当您的源类型和目标类型不完全相同时,似乎会发生这种情况.
在我的例子中,我有一个SQL Server表,其ID字段是INT类型.该值被映射到具有long类型属性的类(Int64).这将导致期望值100被映射到类似668386727769314912.在更改表模式以使ID为BIGINT之后,值始终正确映射.
我建议仔细查看源类型和目标类型,以确保它们完全相同.显然,您希望隐式工作的转换(如Int32到Int64)可能会导致问题.
这是一个重现问题的例子:
public class DataMapperIssue
{
public class Person
{
public long id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
}
public static void run()
{
var table = new DataTable();
table.Columns.Add("id", typeof(int));
table.Columns.Add("first_name", typeof(string));
table.Columns.Add("last_name", typeof(string));
table.Rows.Add(100, "Jeff", "Barnes");
table.Rows.Add(101, "George", "Costanza");
table.Rows.Add(102, "Stewie", "Griffin");
table.Rows.Add(103, "Stan", "Marsh");
table.Rows.Add(104, "Eric", "Cartman");
AutoMapper.Mapper.Reset();
AutoMapper.Mapper.CreateMap<IDataReader, Person>();
var results = AutoMapper.Mapper.Map<IDataReader, IList<Person>>(table.CreateDataReader());
}
}
Run Code Online (Sandbox Code Playgroud)