简体   繁体   中英

To map related entity property to a viewmodel property using Automapper

I have User Table, UserParents table, UserMarks table and UserGrades Table. I am trying to use automapper to map a few of the properties to my view model.

The User table Model :

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; } 
}

My ViewModel: This contains a portion of the fields from each of the four table.

public class UserViewModel
{
    public string UserId{get;set;}
    //From UserParents table
    public string UserParentName{get;set;}
}

My query :

 var user = context.User
           .Include(i => i.UserParents)
           .Include(i => i.UserMarks)
           .Include(i => i.UserGrades)
           .Where(i =>i.userId == userId).FirstOrDefault();

And automapper:

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();

So as in the commented portion of the code, why can't I directly map vm.UserParentName directly to entity.UserParents.UserParentName ?

Is there any other way of doing it?

Change your configuration like so:

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();

The map betwen m.UserId and entity.User Id is not needed, Automapper will do this automatically.

The map for UserParentName, I'm not exactly sure why you would want to get the first in the list of them, but if that is definitely the case then just use the code above to fetch it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM