// combine User and Membership entities into a single class
public class CombinedEntities
{
public User u { get; set; }
public Membership m { get; set; }
}
// view model class
public class MyViewModel
{
public int Id { get; set; }
public Guid UserGuid { get; set; }
public string Username { get; set; }
public string Name { get; set; }
//... other properties omitted
}
// linq
var users = from u in dc.Users
join m in dc.Memberships on u.UserId equals m.UserId
select new CombinedEntities
{
u = u,
m = m,
};
// automapper config and mapping
var config = new MapperConfiguration(c =>
{
c.CreateMap<CombinedEntities, MyViewModel>()
.ForMember(x => x.Id , y => y.MapFrom(s => s.u.Id))
.ForMember(x => x.UserGuid, y=> y.MapFrom(s => s.u.UserGuid));
// should I keep adding more mapping here??
});
var mapper = config.CreateMapper();
var viewModels = mapper.Map<List<CombinedEntities>, List<MyViewModel>>(users.ToList());
我想知道我是否应该继续在那里添加映射。我不认为只有几个属性会让我感到困扰,但如果我们谈论几十个,那么这样做可能非常耗时,而且代码看起来也很臃肿。
现在,我可以想到1)分解CombinedEntities
类并仅保留其中的属性; 2)根本不使用AutoMapper,直接从linq输出MyViewModel
列表。
也许有更好的方法可以做到这一点。有什么建议?