首页 > 解决方案 > 使用 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 ?

还有其他方法吗?

标签: c#entity-frameworkautomapper

解决方案


像这样更改您的配置:

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 的映射,我不完全确定您为什么要获得它们列表中的第一个,但如果确实如此,那么只需使用上面的代码来获取它。


推荐阅读