自动映射投影 - 查看模型的多个实体

时间:2016-05-17 03:45:12

标签: c# asp.net linq automapper

// 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列表。

也许有更好的方法可以做到这一点。有什么建议?

0 个答案:

没有答案