C# 使用automapper将ViewModel映射到模型
我在Automapper使用这种型号时遇到了问题C# 使用automapper将ViewModel映射到模型,c#,automapper,C#,Automapper,我在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 st
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; }
}
这个视图模型
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);
}
//转换为模型
公共静态联系人转换器ContactModel(此ContactView ContactView)
{
返回Mapper.Map(contactView);
}
//转换为视图模型
公共静态联系人视图转换为联系人视图(此联系人)
{
返回Mapper.Map(联系人);
}
为什么转换为模型(ConvertToContactModel)方法不起作用???请确保在映射某些对象之前创建映射。您应该在应用程序启动时使用此代码(
Main
method,或在Global.asax中使用application\u start
):
Mapper.CreateMap();
CreateMap();
不起作用不是很清楚。。。(仍然不清楚:你说的不工作是什么意思?抛出错误,结果不是你想要的吗?)Mapper.CreateMap()
反之亦然?我不明白你的意思,我在单独的类中调用了映射方法:public void CreateContact(CreateContactRequest请求){ContactView contact=new ContactView();contact modelContact=contact.convertoContactModel();_contactRepository.Add(modelContact);_unitOfWork.Commit();}谢谢,您解决了它,thanks@ehsan请记住把它标为答案。
Mapper.CreateMap<ContactView, Contact>();
Mapper.CreateMap<Contact, ContactView>();