简体   繁体   English

AutoMapper - 自定义映射

[英]AutoMapper - Custom Mappings

I am having troubles setting up a custom mapping from my DB entity to my view model using AutoMapper. 我在使用AutoMapper设置从我的数据库实体到我的视图模型的自定义映射时遇到了麻烦。

My goal is to map the ApplicationUser to my ApplicationUserViewModel . 我的目标是将ApplicationUser映射到我的ApplicationUserViewModel

I am returning the list of users like this: 我正在返回这样的用户列表:

return View(Mapper.Map<IEnumerable<ApplicationUserViewModel>>(_userRepository.GetAllUsersWithRoles()));

In the Startup.cs my AutoMapper configuration includes the below: 在Startup.cs中,我的AutoMapper配置包括以下内容:

Mapper.Initialize(config =>
{
   ...
   config.CreateMap<ApplicationUserViewModel, ApplicationUser>().ReverseMap();
});

And I basically want to tell AutoMapper to automatically set the below property of my ViewModel class (IsConnectedToFacebook) to true if the ApplicationUser entity from the DB has a Login stored against it with the provider facebook. 我基本上想告诉AutoMapper自动将我的ViewModel类(IsConnectedToFacebook)的下面属性设置为true,如果来自数据库的ApplicationUser实体有一个与提供者facebook存储的登录名。 So somethink like this: 所以有人想这样:

viewmodel.IsConnectedToFacebook = user.Logins.Any(login => login.LoginProvider == "Facebook");

Here the view model: 这里的视图模型:

public class ApplicationUserViewModel
{
   ...
   public bool IsConnectedToFacebook { get; set; }
}

Thank you very much for your help! 非常感谢您的帮助!

Nik

I got it working with the below: 我得到了以下工作:

config.CreateMap<ApplicationUser, ApplicationUserViewModel>()
                    .ForMember(dest => dest.IsConnectedToFacebook,
                        src => src.MapFrom(s => s.Logins.Any(login => login.LoginProvider == "Facebook")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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