使用自动映射器将相关实体属性映射到viewmodel属性

时间:2019-07-31 14:23:46

标签: c# entity-framework automapper

我有用户表,UserParents表,UserMarks表和UserGrades表。我正在尝试使用自动映射器将一些属性映射到我的视图模型。

User表模型:

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?

还有其他方法吗?

1 个答案:

答案 0 :(得分:1)

像这样更改您的配置:

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和实体之间的映射。不需要用户ID,Automapper会自动执行此操作。

UserParentName的映射,我不确定您为什么要在它们的列表中排第一,但是如果确实如此,那么只需使用上面的代码即可获取。