I have following database context which I use with Entitry Framework
public class MainContext: DbContext
{
public MainContext()
: base("name=MainContext")
{ }
public virtual DbSet<Device> Devices { get; set; }
public virtual DbSet<Point> Points { get; set; }
}
With following Domain model
public class Point
{
[Key]
public int Id { get; set; }
public string Info { get; set; }
public DateTime FixTime { get; set; }
public int DeviceId { get; set; }
public virtual Device Device { get; set; }
}
public class Device
{
[Key]
public int Id { get; set; }
public int SomeValue { get; set; }
public virtual ICollection<Point> Points { get; set; }
public bool IsActive()
{
Point lastPoint = Points.LastOrDefault();
if (lastPoint == null)
{
return false;
}
else
{
var diff = DateTime.Now - lastPoint.FixTime;
if (diff.TotalSeconds > 10 )
{
return false;
}
else
{
return true;
}
}
}
}
I'm facing huge performance problem calling IsActive() method in the Device class. As far as I can see that it because of calling Points.LastOrDefault() queries all available database records for the Device instead of the only one. I understand that it's because of using ICollection in my class but that is Entity Framework demand. Is there's any way to query the only record in such situation or it's just me putting the method in a wrong place?