我正在尝试将我的域模型映射到我的MVC MVVM应用程序中的viewModels。这是我的Auto Mapper配置的代码
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<BookStoreMappingProfile>();
});
}
}
映射档案:
public class BookStoreMappingProfile: Profile
{
public static MapperConfiguration InitializeAutoMapper()
{
MapperConfiguration config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Book, BookListViewModel>();
});
return config;
}
}
Global.asax中
//AutoMapper Configuration
AutoMapperConfiguration.Configure();
我的控制器代码是:
public ActionResult Index()
{
IEnumerable<Book> Books = _bookService.GetAllBooks().ToList();
IEnumerable<BookListViewModel> BookListViewModel = Mapper.Map<IEnumerable<Book>, IEnumerable<BookListViewModel>>(Books);
return View(BookListViewModel);
}
BookListViewModel.cs
public class BookListViewModel
{
[DisplayName("Name")]
public string Name { get; set; }
[DisplayName("ISBN")]
public string ISBN { get; set; }
[DisplayName("Price")]
public double Price { get; set; }
[DisplayName("Rating")]
public double Rating { get; set; }
[DisplayName("Publisher")]
public string Publisher { get; set; }
}
Book.cs
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string ISBN { get; set; }
public double Price { get; set; }
public double Rating { get; set; }
public string Publisher { get; set; }
public DateTime YearPublished { get; set; }
public string Edition { get; set; }
public int CategoryId { get; set; }
public virtual Category Categories { get; set;}
}
当我尝试在控制器中获取我的Index方法时,抛出此异常:
尝试通过方法'AutoMapper.MapperConfiguration.FindClosedGenericTypeMapFor(AutoMapper.TypePair,AutoMapper.TypePair)'来访问方法'AutoMapper.MapperConfiguration + <> c__DisplayClass69_0.b__0(AutoMapper.ProfileMap)'失败。
这是方法访问异常,但我不知道如何解决问题。有人能让我了解那里发生的事情吗?
我也遇到了同样的问题,我正在使用.NET 4.5。
经过一些搜索和跟踪和错误后,我发现问题出在System.ValueTuple上,然后我降级到Automapper 6.22(它没有依赖System.ValueTuple),现在我可以配置它了,一切正常精细。