0
我使用automapper將數據集映射到我創建的對象的IEnumerable。Automapper:將字符串轉換爲數據集的日期時間
我有一個數據集,看起來像(testcode):
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將映射我的數據集到我的對象沒有問題。
我已經調整了我的代碼,但依然出現,但仍然沒有用我的轉換器類(更新可見在原來的職位) – Selketjah
@Selketjah,u能請張貼控制檯應用程序中的完整示例代碼。這只是讓我感到困惑。 –
我在我原來的帖子中發佈了完整的代碼 – Selketjah