Today I come across a very strange error. I have the following method:
public IQueryable<AspNetUserDetails> GetDetails()
{
return this.Get()
.Include(q => q.AspNetRoles)
.OrderBy(q => q.UserName)
.Select(q => new AspNetUserDetails()
{
AspNetUser = q,
Roles = q.AspNetRoles,
StoreAdmin = q.Store,
});
}
(in the database, AspNetUser has AdminStoreId column that allows null, and is a foreign key to primary key of table Store)
In my caller, I have this code to convert to ViewModel (it has the same field names as the Entity):
public async Task<IEnumerable<AspNetUserDetailsViewModel>> GetDetails()
{
return await this.BaseService.GetDetails()
.ProjectTo<AspNetUserDetailsViewModel>(this.AutoMapperConfig)
.ToListAsync();
}
I recieved NullReferenceException at the ProjectTo method. The ProjectTo method is of AutoMapper, and the problem also happens if I use normal Select statement, so it has nothing to do with AutoMapper. I have already solved the problem by changing the Entity Select statement to this:
.Select(q => new AspNetUserDetails()
{
AspNetUser = q,
Roles = q.AspNetRoles,
StoreAdmin = q.AdminStoreId == null ? null : q.Store,
});
My question is: why? Shouldn't q.Store is already null if it has no reference?