C#AutoMapper,如何映射组计数

时间:2018-05-16 09:00:20

标签: c# automapper

我的模特:

public class StatusDetailsViewModel
{
    public string Status { get; set; }
    public long CountNo { get; set; }
}

我的功能是获取数据:

public List<StatusDetailsViewModel> CheckMeetingStatus(long actionId)
{
     List<StatusDetailsViewModel> statusDetails;

     var statuses = _igniteDb.myTable.Where(a => a.actionId == actionId)
                .GroupBy(a => new { a.Status, a.ElectionGroup }).GroupBy(c => new { c.Key.Status})
                .Select(b => new { Status = b.Key.Status, CountNo = b.Count()}).ToList();

     //How to Map statuses to statusDetails??

     return statusDetails;
}

我正在尝试使用自动映射器来实现这一目标。但我不知道如何配置我的映射器。有任何想法吗?

2 个答案:

答案 0 :(得分:1)

仅仅因为您要返回List<StatusDetailsViewModel>,这里不需要AutoMapper,只需直接使用您的视图模型投影数据,如下所示:

List<StatusDetailsViewModel> statusDetails = _igniteDb.myTable.Where(a => a.actionId == actionId)
     .GroupBy(a => new { a.Status, a.ElectionGroup })
     .GroupBy(c => new { c.Key.Status})
     .Select(b => new StatusDetailsViewModel { /* <--- Here you instantiate your view model */
          Status = b.Key.Status, 
          CountNo = b.Count()}
     ).ToList();

答案 1 :(得分:1)

为什么必须在代码中映射。您可以创建StatusDetailsViewModel的对象,而不是创建匿名类型。将select语句更改为Select(b => new StatusDetailsViewModel() { Status = b.Key.Status, CountNo = b.Count()}

如果您想使用 AutoMapper ,则应在定义地图/配置文件时定义源类型和目标类型。您无法使用AutoMapper映射匿名类型。

您创建StatusDetailsViewModel对象的代码(不使用Automapper,因为您不需要您要求的代码)

public List<StatusDetailsViewModel> CheckMeetingStatus(long actionId)
{
     List<StatusDetailsViewModel> statusDetails;

     var statuses = _igniteDb.myTable.Where(a => a.actionId == actionId)
                .GroupBy(a => new { a.Status, a.ElectionGroup }).GroupBy(c => new { c.Key.Status})
                .Select(b => new StatusDetailsViewModel () { Status = b.Key.Status, CountNo = b.Count()}).ToList();

     //How to Map statuses to statusDetails??

     return statusDetails;
}