I'm trying to auto project from SQL server with Automapper some data into my view models.
The view model I have is:
public sealed class WorkstationViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string OccupiedByName { get; set; }
}
And the code I'm trying to use is:
Mapper.CreateMap<Workstation, WorkstationViewModel>()
.ForMember(T => T.OccupiedByName, T => T.MapFrom(W =>
W.Sessions.AsQueryable().Select(E => E.StaffMember.Name).SingleOrDefault()));
Two properties Id
and Name
are auto-projected as they have equal names in Workstation
class.
The exception I get on some codelines like this
var model = WorkstationsRepository.GetAll().Project()
.To<WorkstationViewModel>().SingleOrDefault();
is some weird object reference is null
exception and on the top of the stack trace there are some automapper's CreateExpression<>
methods which gives me a conclusion that the automapper cannot generate a good one expression to translate it to SQL code.
When I use simple maps, like .Name
to .Category.Name
or other one-item retrievals from the SQL table, it works perfectly. All I need is to get access to multiple items while projecting the sequence via Automapper.