I have the following model classes:
Sensor
{
public int Id { get; set; }
public string Name { get; set; }
public bool Enbaled { get; set; }
public int SensorTypeId { get; set; }
pubic SensorType SensorType { get; set; }
}
SensorType
{
public int Id { get; set; }
public string Name { get; set; }
}
SensorDto
{
public int Id { get; set; }
public string Name { get; set; }
public string SensorTypeName { get; set; }
}
In my controller, I am trying to select the sensor model directly from the database. We are using our own binder class, as our Blazor view cannot have any references to our database model.
Here is my SensorDtoBinder
class:
public class SensorDtoBinder : IDtoBinder<SensorDto, Sensor>
{
public SensorDto Bind(Sensor dbItem)
{
return new SensorDto()
{
Id = dbItem.Id,
Name = dbItem.Name,
SensorTypeName = dbItem.SensorType.DisplayName
}
}
}
Here is my calling code:
// get base query
var query = _db.Sensors.Where(x => x.Enabled);
// Package
var response = await query.Select(x => new SensorDtoBinder().Bind(x)).ToListAsync();
The issue is that when I run this, SensorTypeId
has a value, however SensorType
is null.
If I add includes it seems to work, however, I am under the impression that when explicitly selecting (ie NOT lazy loading) you do not need includes). This is a large reason why we went with a specific Dto item per action method, so we could select exactly what we need out the database.