我在使用此模型的Automapper中遇到了麻烦
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string MessageTitle { get; set; }
public string MessageBody { get; set; }
public string MessageTime { get; set; }
}
和这个ViewModel
public class ContactView
{
public string Name { get; set; }
public string Email { get; set; }
public string MessageTitle { get; set; }
public string MessageBody { get; set; }
public string MessageTime { get; set; }
}
这是我的转换方法:
//Convert to Model
public static Contact ConvertToContactModel(this ContactView contactView)
{
return Mapper.Map<ContactView, Contact>(contactView);
}
//Convert to ViewModel
public static ContactView ConvertToContactView(this Contact contact)
{
return Mapper.Map<Contact, ContactView>(contact);
}
为什么转换为Model(ConvertToContactModel)方法不起作用?
答案 0 :(得分:2)
确保在映射某些对象之前创建映射。您应该在应用程序启动时使用此代码(Main
方法,或在 Global.asax 中使用Application_Start
):
Mapper.CreateMap<ContactView, Contact>();
Mapper.CreateMap<Contact, ContactView>();