Check if there is 0 rows in Entity Framework

Viewed 52

I have this line of code that i want to return true/false if no "Sensor" exists.

I know for sure that i have 1 sensor with no data, and then i want to add data to it if it doesn't have data already.

var dataExsist = Context.SensorLogs
                        .FirstOrDefault(a => a.SensorId == sensor.SensorId);

It will find all the sensors that have data, but not the one without data.

I tried with .Count to see if it would show 0, but it doesn't.

Any help is greatly appreciated.

1 Answers

I think what you need to use is .Any();

using System.Linq;

bool doesExists = Context.SensorLogs.Any(a => a.SensorId == sensor.SensorId);

bool doesNotExists = !Context.SensorLogs.Any(a => a.SensorId == sensor.SensorId);
Related