AutoMapper可以将对象映射到相同类型的模型属性
我正在尝试改进 MVC 3 模型和视图(主要是 CRUD)之间的数据流。我采取了使用 ViewModel 和 FormModel 的方法。我的 ViewModel 包含表示视图 FormData、DropDownLists 等所需的所有内容。FormModel 仅包含由表单提交并更新记录所需的 FormData 字段。
我的问题是我可以使用 AutoMapper 将 UserDto 信息映射到 ViewModel 中的 FormData 字段吗?
显然,我下面的映射只是两个对象之间的映射,而不是对象到属性的映射,但我尝试使用“.ForMember”映射选项,但它们同样适用于对象成员,而不是对象到对象成员。我还查看了自定义类型转换器,但不确定这是否是正确的方法。
Mapper.CreateMap<UserDto, UserViewModel>();
Mapper.CreateMap<UserViewModel, UserDto>();
public class UserViewModel
{
public User FormData { get; set; }
// DropDownLists
// Other view specific data
}
public class UserFormModel
{
public int UserId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Age { get; set; }
[Required]
public string Email { get; set; }
}
任何帮助将不胜感激。
I am attempting to improve my data flow between my MVC 3 Model and Views (mainly CRUD). I have taken the approach of using ViewModels and FormModels. My ViewModel contains everything it need to represent the view FormData, DropDownLists etc. The FormModel simply contains the FormData fields that are submitted by the form and are needed to update a record.
My question is can I use AutoMapper to map UserDto information onto my FormData field in my ViewModel?
Obviously my mapping below is only mapping between the two object and not an object to property but I have tried using the ‘.ForMember’ mapping options but they are again for object members not an object to an object member. I have also looked at Custom Type Convertors but not sure if this is the right way to go.
Mapper.CreateMap<UserDto, UserViewModel>();
Mapper.CreateMap<UserViewModel, UserDto>();
public class UserViewModel
{
public User FormData { get; set; }
// DropDownLists
// Other view specific data
}
public class UserFormModel
{
public int UserId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Age { get; set; }
[Required]
public string Email { get; set; }
}
Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要创建 FormData 属性类型的映射,然后告诉 AutoMapper 使用此映射。
(以下内容可能无法编译;我正在重新创建我的工作机器并根据内存工作)。
You need to create the map to the FormData property type and then tell AutoMapper to use this map.
(The following will likely not compile; I'm in the process of recreating my work machine and am working from memory).