如何在存储库中使用automapper?

时间:2016-11-23 16:51:05

标签: c# asp.net-mvc kendo-ui repository automapper

在我的存储库中,我想使用视图模型,因为我返回的数据非常繁重,无法序列化。我正在为我的KendoUI Grid返回这些数据,但是尽管正确引用,映射仍然会丢失错误。

我有一个名为VesselsViewModel的ViewModel:

视图模型

namespace MyProject.ViewModels
{
    public class VesselsViewModel
    {
        [Display(Name = "ID")]
        public int vessel_idx { get; set; }

        [Display(Name = "Name")]
        public string vessel_name { get; set; }

        [Display(Name = "IMONO")]
        public string imono { get; set; }

        [Display(Name = "Type")]
        public string vessel_type { get; set; }
    }
}

我像这样访问我的控制器中的viewmodel(使用Automapper):

索引控制器

public ActionResult Index()
    {
        var vessels = _repository.GetAll();
        var vm = Mapper.Map<VesselsViewModel>(vessels);
        return View(vm);
    }

当我运行我的项目时,我收到以下错误:

错误

{"Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nList`1 -> VesselsViewModel\r\nSystem.Collections.Generic.List`1[[MyProject.Models.tbl_vessels, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> MyProject.ViewModels.VesselsViewModel\r\n\r\nDestination path:\r\nVesselsViewModel\r\n\r\nSource value:\r\nSystem.Collections.Generic.List`1[MyProject.Models.tbl_vessels]"}

我有Global.asax中指定的映射,但似乎没有什么区别。

映射Global.asax

Mapper.CreateMap<tbl_vessels, VesselsViewModel>().ReverseMap();

这是我的存储库供参考:

Repository.cs

public class Repository<T> : IRepository<T> where T : class
{
    private seabrokersEntities db;
    private DbSet<T> dbSet;

    public Repository()
    {
        db = new seabrokersEntities();
        dbSet = db.Set<T>();
    }

    //
    // GET : All
    public IEnumerable<T> GetAll()
    {
        return dbSet.ToList();
    }
}

IRepository.cs

 public interface IRepository<T> where T : class
    {
        IEnumerable<T> GetAll();        
        T GetById(object Id);
        void Insert(T obj);
        void Update(T obj);
        void Delete(Object Id);
        void Save();
    }

我做错了什么可能导致了这个问题,或者我错过了什么?我知道automapper已经改变了它处理映射的方式,所以我可能需要改变我正在做的事情但不确定如何。

作为旁注,如果我手动映射出类,它可以正常工作。

手动制图

IEnumerable<VesselsViewModel> model = vessels.Select(
            x => new VesselsViewModel
            {
                vessel_idx = x.vessel_idx,
                vessel_name = x.vessel_name,
                vessel_type = x.vessel_type
            });

非常感谢

0 个答案:

没有答案
相关问题