How to map poco to JSON using Automapper
In my MVC 2 application I have a typical method that calls a web 开发者_如何转开发service, builds a JSON data object and returns it to the view.
Everything works fine, but I was wondering if there is a way to do the mapping with Automapper so I can remove the ugly code from my controller. Thanks in advance
Here is my Action method
public virtual ActionResult AllErrors(string sidx, string sord,
int page=1, int rows=10)
{
var pageSize = rows;
var pageNumber = page;
var orderBy = string.Format("{0} {1}", sidx, sord);
var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);
int index = 0;
var list = new List<object>();
errors.ForEach(e => list.Add(
new {
i = index++,
cell = new[]
{
e.IngestionErrorId.ToString(),
e.RunId.ToString(),
e.ProcessDate.ToShortDateString(),
e.Status,
e.ErrorDetails
}
}));
var jsonData = new
{
total = totalPages,
page = pageNumber,
records = result.TotalRows,
rows = list.ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I solved it using the ConstructUsing method of AutoMapper. Here is my map
public void CreateMap()
{
Mapper.CreateMap<List<IngestionErrorDataContract>, object[]>()
.ConvertUsing(
errors =>
{
int index = 0;
var list = new List<object>();
errors.ForEach(e => list.Add(
new
{
i = index++,
cell = new[]
{
e.IngestionErrorId.ToString(),
e.RunId.ToString(),
e.ProcessDate.ToShortDateString(),
e.Status,
e.ErrorDetails
}
}));
return list.ToArray();
});
}
and here is my action method now
public virtual ActionResult AllErrors(string sidx, string sord, int page=1, int rows=10)
{
var pageSize = rows;
var pageNumber = page;
var orderBy = string.Format("{0} {1}", sidx, sord);
var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);
var jsonData = new
{
total = totalPages,
page = pageNumber,
records = result.TotalRows,
rows = mapper.Map<List<IngestionErrorDataContract>,object[]>(errors)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Much better I think
精彩评论