title: How to get the min and max value from a dbcontext
body: <p>I am storing sensor data in a sql database. Each entry has a device_id, timestamp, value and some other properties. </p>
  
  <p>I want to implement a webapi function which returns the first and last event that i have received from a sensor device. So my serialized DTO should be something like this:
  <code>{ "start": &lt;timestamp:long&gt;, "end": &lt;timestamp:long&gt;, "deviceid": &lt;someid:string&gt;}</code></p>
  
  <p>I am using Entityframework Core to access my database. I can get a list of unique device id's without any problems. If i try to get the min or max value of the timestamp per device, my dbcontext throws an invalid operation exception.</p>
  
  <p>I tried several things like this:</p>
  
  <pre><code>var deviceList=_context.Data.Select(d=&gt;d.DeviceId).Distinct();
  foreach(string deviceId in deviceList)
  {
     var max = _context.Data.Where(g=&gt;g.DeviceId==deviceId).Max(c=&gt;c.Timestamp);
     var min ...
  }
  </code></pre>
  
  <p>This snippet throws an invalid operation exception from the clr. As far as i understand this, it creates a statement which is not executed on the server side. My question is how i can create a query that requests the min and max value (per device) on a dbcontext? Also i would like know what the recommended way is to implement this, so that it is not executed on the client side.</p>
  
  <p>Thank you Werner.</p>