0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Zapnologica
  • 22,170
  • 44
  • 158
  • 253
  • 1
    Calls like `new SensorDtoBinder().Bind(x)` inside query expression tree are not translatable and will normally fail. Here it "works" because it is the final `Select`, so EF Core executes it client side. You need different approach using expressions. Similar to AutoMapper projections (`ProjectTo` vs `Map`). – Ivan Stoev Nov 16 '21 at 05:55
  • @IvanStoev So would this work if I changed it to: select(x=> new {Type= x.sensorType.Name) – Zapnologica Nov 16 '21 at 08:31
  • 1
    Yes, it would work. – Ivan Stoev Nov 16 '21 at 08:34
  • Probably you will find it [helpful](https://stackoverflow.com/a/66386142/10646316) – Svyatoslav Danyliv Nov 16 '21 at 08:48

0 Answers0