我想使用AutoMapper之类的代码来代替手动映射。
我有两个表User和Role,并且都使用RoleID映射。现在的问题是,如果我从用户那里获取记录,那么它只会给我 RoleID 而不是 ROLENAME 即可。所以我试图用自定义类获取结果并使用for循环(手动)映射每个实体。
任何人都可以帮助您自动优化此手动代码。因为我有超过15个关系表。
// M O D E L
public class RoleModel : IRoleModel
{
public Guid RoleID { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
}
public class UserModel : IUserModel
{
public Guid UserID { get; set; }
public Guid RoleID { get; set; }
public string UserName { get; set; }
}
public class UserRoleModel
{
public Guid UserID { get; set; }
public string UserName { get; set; }
public string Description { get; set; }
public Guid RoleID { get; set; }
public string RoleName { get; set; }
}
// C O N T R O L L E R
public class UsersController : Controller
{
private IUserService _UserService;
public UsersController()
: this(new UserService())
{
}
public UsersController(IUserService UserService)
{
_UserService = UserService;
}
public ActionResult Index()
{
IList<UserRoleModel> users = _UserService.GetUsersWithRole();
return View(users);
}
public ActionResult Create()
{
return View();
}
}
// S E R V I C E
public class UserService : ServiceBase<IUserService, User>, IUserService
{
private IUserRepository _UserRepository;
public UserService()
: this(new UserRepository())
{
}
public UserService(IUserRepository UserRepository)
{
_UserRepository = UserRepository ?? new UserRepository();
}
public IList<UserRoleModel> GetUsersWithRole()
{
IList<User> users = _UserRepository.GetAll();
IList<UserRoleModel> userswithrol = new List<UserRoleModel>();
/* I would like to use AUTO MAPPER instead of MANUAL MAPPING*/
foreach (User u in users)
{
UserRoleModel ur = new UserRoleModel();
ur.UserID = u.UserID;
ur.UserName = u.UserName;
ur.Description = u.Description;
ur.RoleID = u.RoleID.Value;
ur.RoleName = u.Role.RoleName;
userswithrol.Add(ur);
}
/**/
return userswithrol;
}
private IList<UserModel> GetAll()
{
IEnumerable<User> alliance;
if (whereCondition != null)
alliance = _UserRepository.GetAll(whereCondition);
else
alliance = _UserRepository.GetAll();
UserListModel model = new UserListModel();
model.UserList = new List<UserModel>();
AutoMapper.Mapper.CreateMap<User, UserModel>().ForMember(dest => dest.UserID, opt => opt.MapFrom(src => src.UserID));
model.UserList = AutoMapper.Mapper.Map(alliance, model.UserList);
return model.UserList;
}
}
任何答案都将不胜感激!
谢谢,
Imdadhusen
答案 0 :(得分:0)
我使用以下解决方案解决了这个问题:
public IList<UserRoleModel> GetUsersWithRole()
{
IList<User> users = _UserRepository.GetAll();
IList<UserRoleModel> userswithrol = new List<UserRoleModel>();
AutoMapper.Mapper.CreateMap<User, UserRoleModel>()
.ForMember(d => d.UserID, o => o.MapFrom(s => s.UserID))
.ForMember(d => d.RoleName, o => o.MapFrom(s => s.Role.RoleName));
userswithrol = AutoMapper.Mapper.Map(users, userswithrol);
return userswithrol;
}
注意:我刚刚添加了一行代码来实现所需的输出
.ForMember(d => d.RoleName, o => o.MapFrom(s => s.Role.RoleName))
谢谢,
Imdadhusen