使用automapper映射两个数组返回空数组

时间:2014-06-10 06:02:55

标签: c# asp.net-mvc entity-framework automapper

我正在尝试使用Automapper两个数组进行映射,这是一个来自EF和目标我的实体对象的poco对象,这就是我所做的并且总是返回一个空数组:

从Log []到> Model.Log []

   var srcLog = db.Set<Log>().Where(e => e.Id > id).Take(quantity).ToArray();
   var result = Mapper.DynamicMap<Log[], Model.Log[]>(srcLog);

EF日志对象:

 public partial class Log
    {
        public long Id { get; set; }
        public string Member_Id { get; set; }
        public string Message { get; set; }
        public DateTime CreatedDate { get; set; }       
        public virtual Member Member { get; set; }
    }

Model.Log []对象:

 public class Log
    {
        public long Id { get; set; } 
        public string Message { get; set; }
        public DateTime CreatedDate { get; set; }
        public Member Member { get; set; }
    }

1 个答案:

答案 0 :(得分:3)

不要创建Log[]数组映射 - 而只是定义2个实体之间的映射:

var srcLog = new[] {new Log {Id = 1}, new Log {Id = 2}};
Mapper.CreateMap<Log, Model.Log>();//do not map from/to an array

var result = Mapper.Map<Model.Log[]>(srcLog);
Assert.AreEqual(2, result.Length);
Assert.AreEqual(1, result[0].Id);
Assert.AreEqual(2, result[1].Id);//all green!

看来你不能使用泛型或非泛型DynamicMap但是你知道编译时的类型你应该使用CreateMap。有关详细信息,请参阅here