我使用 automapper 将数据集映射到我创建的对象的 IEnumerable。
我有一个看起来像(测试代码)的数据集:
class Program
{
static void Main(string[] args)
{
Mapper.CreateMap<string, DateTimeOffset>().ConvertUsing<StringToDateTimeOffsetConverter>();
Mapper.CreateMap<string, DateTime>().ConvertUsing<StringToDateTimeConverter>();
Mapper.CreateMap<IDataReader, SentMessageListItem>()
.ForMember(dest => dest.SentDate, opt => opt.MapFrom(src => src.GetString(2)))
.ForMember(dest => dest.DeleteDate, opt => opt.MapFrom(src => src.GetString(3)));
var sentmessages = Mapper.Map<IDataReader, IEnumerable<SentMessageListItem>>(Model.DataSet.CreateDataReader());
}
}
public class SentMessageListItem
{
public virtual int Id { get; set; }
public virtual string Subject { get; set; }
public virtual DateTimeOffset SentDate { get; set; }
public virtual DateTime DeleteDate { get; set; }
}
internal class StringToDateTimeOffsetConverter : ITypeConverter<string, DateTimeOffset>
{
public DateTimeOffset Convert(ResolutionContext context)
{
var objDateTime = context.SourceValue;
DateTimeOffset dateTime;
if (objDateTime == null)
{
return default(DateTimeOffset);
}
if (DateTimeOffset.TryParse(objDateTime.ToString(), out dateTime))
{
return dateTime;
}
return default(DateTimeOffset);
}
}
internal class StringToDateTimeConverter : ITypeConverter<string, DateTime>
{
public DateTime Convert(ResolutionContext context)
{
var objDateTime = context.SourceValue;
DateTime dateTime;
if (objDateTime == null)
{
return default(DateTime);
}
if (DateTime.TryParse(objDateTime.ToString(), out dateTime))
{
return dateTime;
}
return default(DateTime);
}
}
public static class Model
{
public static readonly DataSet DataSet = GetDataSet();
private static DataSet GetDataSet()
{
var set = new DataSet();
var table1 = new DataTable();
table1.Columns.Add("id");
table1.Columns.Add("subject");
table1.Columns.Add("sentdate");
table1.Columns.Add("deletedate");
table1.Rows.Add("0", "Subject", "01/01/2013", "01/01/2013");
set.Tables.Add(table1);
return set;
}
}
错误:
Mapping types:
IDataReader -> IEnumerable`1
System.Data.IDataReader -> System.Collections.Generic.IEnumerable`1[[CNH.CSCN.BBS.Entities.Domain.Entities.SentMessageListItem, CNH.CSCN.BBS.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
Destination path:
IEnumerable`1
Source value:
System.Data.DataTableReader
我究竟做错了什么?
该错误是由 datetimeoffset 和 datetime 引起的,因为如果我删除它们,automapper 将我的数据集映射到我的对象没有问题。