I have encountered a LINQ issue and hope that you can help me to figure it out.
Here is what is happening.
- I get an
IQueryable<LicenseEntity>
of entities from the repository. - I look at the fields in these entities and see that they contain valid data. There is a field for a related entity
Customer
in the LicenseEntity. It contains valid data, too, because I loaded it with the LicenseEntity. - I use
.Select
to project each LicenseEntity to a LicenseViewModel. - For each LicenseEntity, a LicenseEntity is passed into
AutoMapper.Mapper.Map
and is loaded into a LicenceViewModel entity. - After all of the entities have been processed, when I look at the list of LicenseViewModels in the debugger, it reports a null reference exception and there are no items to view.
- To determine whether AutoMapper what causing my problem, I replaced it with a
MapMe()
. When I stopped at the return statement in MapMe and looked at thes
parameter, which is the original entity, I found that the data in it is okay except that the customer field is now null. I assume thatSelect
has done something that I don't know about.
How I can make Select
retain all of the information in the original entity when it is doing its projection? Our solution cannot materialize the list because it may be very, very large. I've included my test code below and would really appreciate your help.
// Get the IQueryable<LicenseEntity> list of licenses from the repository.
var list = LicenseRepository.List();
// Convert the IQueryable<LicenseEntity> to an IQueryable<LicenseViewModel>
var vmlist = list.Select(x => MapMe(x, new LicenseViewModel()));
//var vmlist = list.Select(x => AutoMapper.Mapper.Map(x, new LicenseViewModel()));
// This function was used to see the LicenseEntity that was passing into Map().
// I discovered that the entity has all the correct data except for a related
// entity field, which was present in the original LicenseEntity before
public LicenseViewModel MapMe(LicenseEntity s, LicenseViewModel d)
{
return d;
}
The following code works properly however it materializes the entities, which we cannot do.
List<LicenseViewModel> vms = new List<LicenseViewModel>();
foreach (var item in list)
{
var vm = AutoMapper.Mapper.Map(item, new LicenseViewModel());
vms.Add(vm);
}