簡體   English   中英

使用自動映射器將相關實體屬性映射到viewmodel屬性

[英]To map related entity property to a viewmodel property using Automapper

我有用戶表,UserParents表,UserMarks表和UserGrades表。 我正在嘗試使用自動映射器將一些屬性映射到我的視圖模型。

用戶表模型:

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的映射,我不確定您為什么要在它們的列表中獲得第一個,但是如果確實如此,則只需使用上面的代碼即可獲取它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM