我正在尝试将我的域模型映射到我的 MVC MVVM 应用程序中的视图模型。这是我的自动映射器配置的代码
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;
}
}
全球.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; }
}
图书.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)”失败。
这是一个方法访问异常,但我不知道如何解决这个问题。有人能告诉我里面发生了什么吗?