c# - 使用 Automapper 将相关实体属性映射到视图模型属性
问题描述
我有用户表、UserParents 表、UserMarks 表和 UserGrades 表。我正在尝试使用 automapper 将一些属性映射到我的视图模型。
用户表模型:
public partial class User
{
public string UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<UserParents> UserParents { get; set; }
public virtual ICollection<UserMarks> UserMarks { get; set; }
public virtual ICollection<UserGrades> UserGrades { get; set; }
}
我的 ViewModel:这包含四个表中每个字段的一部分。
public class UserViewModel
{
public string UserId{get;set;}
//From UserParents table
public string UserParentName{get;set;}
}
我的查询:
var user = context.User
.Include(i => i.UserParents)
.Include(i => i.UserMarks)
.Include(i => i.UserGrades)
.Where(i =>i.userId == userId).FirstOrDefault();
和自动映射器:
config = new MapperConfiguration(cfg => {
cfg.CreateMap<User,UserViewModel>()
//This works
.ForMember(m => m.UserId,opt =>opt.MapFrom(entity => entity.UserId))
//Can't map vm.UserParentName directly to entity.UserParents.UserParentName and so have to do all of this
.ForMember(vm => vm.UserParentName, opt => opt.MapFrom(entity => entity.UserParents.Select(c =>c.UserParentName).FirstOrDefault()))
.ReverseMap();});
IMapper mapper = config.CreateMapper();
因此,在代码的注释部分中,为什么我不能直接将 vm.UserParentName 直接映射到 entity.UserParents.UserParentName ?
还有其他方法吗?
解决方案
像这样更改您的配置:
config = new MapperConfiguration(cfg => {
cfg.CreateMap<User,UserViewModel>()
//This is actually unnecesseray
//.ForMember(m => m.UserId,opt =>opt.MapFrom(entity => entity.UserId))
// If you only want the first parent name - Not sure on structure of UserParent class so just assuming you have a field "Name"
.ForMember(vm => vm.UserParentName,
opt => opt.MapFrom(entity => entity.UserParents.FirstOrDefault().Name))
.ReverseMap();
});
IMapper mapper = config.CreateMapper();
m.UserId 和 entity.User Id 之间的映射不是必需的,Automapper 会自动执行此操作。
UserParentName 的映射,我不完全确定您为什么要获得它们列表中的第一个,但如果确实如此,那么只需使用上面的代码来获取它。
推荐阅读
- python - 将文本文件读入矩阵python
- powershell - 通过 Powershell 将计划任务部署到多台计算机
- c++ - C++ `std::move` 自定义类型转换为 lambda 捕获
- asp.net-mvc - 如何将日期时间从 mvc 发送到 web api 作为参数?
- c# - 为什么当我尝试点击操作方法时会出错
- java - 在 Java 中打印数字和非数字
- javascript - 如何使用函数更改 Vue 组件按钮颜色?
- javascript - $(window).on('popstate') 在 IE 中不起作用
- c - 检查给定字符串是否是 C 中的#define
- windows - Powershell 备份脚本