我需要一些帮助。我正在使用 ASP.NET 我是初学者的MVC。
我正在编写一个带有数据库和 3 个表的应用程序(2 个表仅用于父子下拉列表,第三个用于从下拉列表中保存数据并填写其他表单(。
我正在使用带有 SQL 的实体框架将我的数据库连接到具有从数据库自动生成的模型 ASP.NET MVC。
我手动制作所有三个表及其字段的视图模型,我需要将所有数据传递给 1 个视图(创建视图(
这是我从家庭控制器收到的代码,我收到错误。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactsViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
// Error happens here
Contact contactModel = Mapper.Map<CountryStateContactsViewModel, Contact>(csvm);
db.Contacts.Add(contactModel);
db.SaveChanges();
return RedirectToAction("Index");
}
这是我得到的错误:
非静态字段、方法或属性"Mapper.Map<CountryStateContactsViewModel,>(CountryStateContactsViewModel( 需要对象引用
为了使用AutoMapper,首先你应该在你的类之间创建映射。
public class ContactProfile {
public AutoMapperProfile() {
CreateMap<CountryStateContactsViewModel,Contact>();
}
}
public class AutoMapperConfiguration {
public static void Initialize() {
Mapper.Initialize(cfg = > {
cfg.AddProfile(new ContactProfile());
});
}
}
最后在你的 Global.asax 中:
AutoMapperConfiguration.Initialize()
根据OP注释,没有自动映射器配置,没有它,AutoMapper无法解析映射。
定义一个接口来抽象映射方法:
public interface IMappingService
{
TDest Map<TSrc, TDest>(TSrc source) where TDest : class;
TDest Map<TSrc, TDest>(TSrc source, TDest dest) where TDest : class;
}
实现接口:
public class MappingService : IMappingService
{
private MapperConfiguration mapperConfiguration;
private IMapper mapper;
public MappingService()
{
mapperConfiguration = new MapperConfiguration(cfg =>
{
// Define here your mapping profiles...
cfg.AddProfile<ViewModelToDomainMappingProfile>();
cfg.AddProfile<DomainToViewModelMappingProfile>();
});
// You may not want to assert that your config is valid, and that's ok.
mapperConfiguration.AssertConfigurationIsValid();
mapper = mapperConfiguration.CreateMapper();
}
public TDest Map<TSrc, TDest>(TSrc source) where TDest : class
{
return mapper.Map<TSrc, TDest>(source);
}
public TDest Map<TSrc, TDest>(TSrc source, TDest dest) where TDest : class
{
return mapper.Map(source, dest);
}
}
现在,您必须定义配置文件(示例(:
public class ViewModelToDomainProfile: Profile
{
public ViewModelToDomainProfile()
{
CreateMap<CountryStateContactsViewModel, Contact>();
}
}
public class DomainToViewModelProfile: Profile
{
public DomainToViewModelProfile()
{
CreateMap<CountryStateContactsViewModel, Contact>();
}
}
最后,在控制器中注入您的 IMappingService:
private readonly IMappingService _mappingService;
public HomeController(IMappingService mappingService) {
_mappingService = mappingService;
}
并像这样使用它:
_mappingService.Map<CountryStateContactsViewModel, Contact>(viewModel);
我喜欢这个解决方案,因为它很好地封装了所有内容。
编辑:@Arsalan Valoojerdi比我快。但是,这样你就有两种不同的方法。
注意:不要忘记在 IoC 容器上定义对 IMappingService 的依赖关系(例如。宁注射(。