如何使用AutoMapper将字符串传递给MVC模型

时间:2014-01-28 11:31:02

标签: asp.net-mvc automapper

我正在尝试在使用AutoMapper生成的视图中包含csv字符串involvedBody,但我无法确定将字符串映射到模型的位置。

我认为它将在控制器中的CreateMap调用中或作为映射中的.ForMember函数,但我无法使其工作。我需要调用InvolvedBodies函数并在模型成为IOrderedEnumerable之前将字符串传递给模型。

这是可能的还是我需要尝试其他的东西?

视图模型

public partial class FamilyInterventionListViewModel
    {
        public int Id { get; set; }
        public int interventionId { get; set; }
        public string interventionCategory { get; set; }
        public string interventionType { get; set; }
        public string outcome { get; set; }
        public string achievement { get; set; }
        public string involvedBody { get; set; }
        public string startDate { get; set; }
        public string endDate { get; set; }
        public string notes { get; set; }  
    }

存储库

 public string InvolvedBodies(int interventionId)
    {
        var q = (from body in context.tEntity
                 where body.tIntervention.Any(b => b.interventionID == interventionId)
                 select body.entityName
                 );

        var ibcsv = string.Join(",", q.ToArray());                       

        return ibcsv;                    
    }

控制器

    public ActionResult InterventionType(int Id, string achievement)
    {
        var model = GetDisplay(Id)
            .Where(m => m.achievement == achievement)
            .OrderByDescending(m => m.startDate)                
            ;           

        return PartialView("_interventionType", model);
    }


//Automapper for display model
private IEnumerable<FamilyInterventionListViewModel> GetDisplay(int Id)
{
    var list = _repo.Get(Id);
    Mapper.CreateMap<tIntervention, FamilyInterventionListViewModel>();
    IEnumerable<FamilyInterventionListViewModel> viewModel = Mapper.Map <IEnumerable<tIntervention>, IEnumerable<FamilyInterventionListViewModel>>(list);            
    return viewModel;
}

映射

Mapper.CreateMap<tIntervention, FamilyInterventionListViewModel>()
    .ForMember(d => d.Id, o => o.MapFrom(s => s.interventionID))
    .ForMember(d => d.interventionCategory, o => o.MapFrom(s => s.tOutcome.tInterventionCategory.InterventionCategory))
    .ForMember(d => d.interventionType, o => o.MapFrom(s => s.tInterventionType.interventionType))
    .ForMember(d => d.outcome, o => o.MapFrom(s => s.tOutcome.outcome))
    .ForMember(d => d.achievement, o => o.MapFrom(s => s.tAchievement.achievement))
    .ForMember(d => d.involvedBody, o => o.MapFrom(s => s.tEntity.Select(m => m.entityName)))
    ;

1 个答案:

答案 0 :(得分:1)

我无法使用Automapper找到解决方案,因此在使用以下方法创建模型后,已恢复为手动映射csv字符串:

foreach (var item in model)
{
    item.involvedBody = _repo.InvolvedBodies(item.interventionId);
}

我有兴趣知道这是否被视为良好做法,或者我是否应该使用其他技术。