就想把查询结果扔到AotoMapper里做转换,研究了半天,用Tuple可以实现
var messages = from p in _db.ServiceMessages
group p by p.ServiceID into g
select new
{
ServiceID = g.Key,
LastMessageDate = g.Max(service => service.Created)
};
var results = (from p in _db.Services
join q in messages on p.ID equals q.ServiceID into serviceMessages
from s in serviceMessages.DefaultIfEmpty()
select new Tuple<Service, DateTime?>(p, s.LastMessageDate))
.ProjectTo<ServiceListDTO>(_mapper.ConfigurationProvider);
CreateMap<Tuple<Service, DateTime?>, ServiceListDTO>()
.ForAllMembers(opt =>
{
if (!opt.DestinationMember.Name.Equals("LastMessageDate"))
{
opt.MapFrom($"Item1.{opt.DestinationMember.Name}");
}
else
{
opt.MapFrom($"Item2");
}
});
会造成的问题:results不再是一个可扩展在Querable对象,慎用。