1

I use LINQ to entity to retrive records from table and there related records from another table.

Here is my tables with relation:

enter image description here

And here is my LINQ to entity to retrieve records from Sensors Measure and related table alert description.

public IEnumerable<SensorsMeasure> GetSensorsMeasureWithAlertDescription()
{
    return SensorObservationEntities.SensorsMeasures.Include(d => d.AlertsDescription.AlertDescription).ToList();
}

But on the query above I get this error:

A specified Include path is not valid. The EntityType 'SensorObservationModel.AlertsDescription' does not declare a navigation property with the name 'AlertDescription'.

Any idea why I get the error above and how to fix it?

Michael
  • 13,950
  • 57
  • 145
  • 288

1 Answers1

2

That's because AlertDescription is not navigation property of AlertsDescription type - it's just regular property, so you don't need to include it. Just do:

public IEnumerable<SensorsMeasure> GetSensorsMeasureWithAlertDescription()
{
    return SensorObservationEntities.SensorsMeasures.Include(d => d.AlertsDescription).ToList();
}
Evk
  • 98,527
  • 8
  • 141
  • 191
  • and how do I get the alert description property from AlertsDescription table? – Michael Apr 09 '16 at 16:26
  • Just access AlertsDescription.AlertDescription property of SensorsMeasure object. Because you loaded AlertsDescription with Include - you can access all it's properties (of course assuming SensorsMeasure has associated AlertsDescription in the first place - otherwise this property will be null) – Evk Apr 09 '16 at 16:28
  • You seems to be a bit confused thinking Include is somehow related to regular properties, but it's not - every EF entity will have all it's regular properties always loaded, no matter what. You can only control if navigation properties will be loaded, with Include. – Evk Apr 09 '16 at 16:31
  • is there any way to get only alertDescription fild and not all record?\ – Michael Apr 09 '16 at 16:56
  • With Include - don't think so. If you want custom shape for your data - you need to use Select and project into custom or anonymous type, but in this case you won't be able to track changes to this entity and so won't be able to easily update it. If you are not going to do this anyway (you only return SensorsMeasure for reading) - just Select only the properties you need (from both SensorsMeasure object and any children objects like AlersDescritpion) into custom type and return this type instead. But in your model, AlertDescription is the only column in AlertsDescription table anyway. – Evk Apr 09 '16 at 17:16