2012-11-06 9 views
5

Ho un view con dati e ho bisogno di recuperare i dati solo dagli ultimi 7 giorni. So che c'è una funzione per questo se stavo usando query SQL. ma sto usando Linq.Recupero dati dal database negli ultimi 7 giorni utilizzando linq

Ecco il mio codice:

   try 
       { 
       var query = (from bwl in mg.BarcodeWithLocation 
          select new 
          { 
           RequestID = bwl.RequestID, 
           Barcode = bwl.Barcode, 
           adrid = bwl.AdrID, 
           name = bwl.Name, 
           street = bwl.Street, 
           houseno = bwl.HouseNo, 
           postal = bwl.Postal, 
           city = bwl.City, 
           country = bwl.Country, 
           latitudetxt = bwl.Latitude == "" ? "Location Unknown" : "View Map Location", 
           latitude = bwl.Latitude, 
           longitude = bwl.Longitude, 
           date = bwl.ReceivedDate 
          }); 

       this.Grid.DataSource = query; 
       this.Grid.DataBind(); 
       } 
       catch (Exception exception) 
       { 
         Console.WriteLine("ERROR in GetNoLocationScan() method. Error Message : " + exception.Message); 
       } 

qualcuno può dirmi come faccio questo in Linq?

risposta

8

È possibile utilizzare DateTime.Now.AddDays(-7) per ottenere il record più vecchio di sette giorni rispetto alla data corrente. Oppure puoi usare Datime.Today.AddDays (-7) se vuoi la parte del tempo e iniziare dopo le 12:00.

var query = (from bwl in mg.BarcodeWithLocation 
       where(bwl.ReceivedDate > DateTime.Now.AddDays(-7)) 
         select new 
         { 
          RequestID = bwl.RequestID, 
          Barcode = bwl.Barcode, 
          adrid = bwl.AdrID, 
          name = bwl.Name, 
          street = bwl.Street, 
          houseno = bwl.HouseNo, 
          postal = bwl.Postal, 
          city = bwl.City, 
          country = bwl.Country, 
          latitudetxt = bwl.Latitude == "" ? "Location Unknown" : "View Map Location", 
          latitude = bwl.Latitude, 
          longitude = bwl.Longitude, 
          date = bwl.ReceivedDate 
         }); 
+1

Penso che non è possibile utilizzare DateTime.Now.AddDays (-1) all'interno LINQ to Entity – Uriil

+0

o 'DateTime.Today.AddDays (-7)', se non si desidera filtrare per tempo –

+0

@Adil Questa query funziona con datetime ?? –

1

Prova questo:

var dt = DateTime.Now.AddDays(-7); 
    var query = (from bwl in mg.BarcodeWithLocation 
       where bwl.ReceivedDate > dt 
         select new 
         { 
          RequestID = bwl.RequestID, 
          Barcode = bwl.Barcode, 
          adrid = bwl.AdrID, 
          name = bwl.Name, 
          street = bwl.Street, 
          houseno = bwl.HouseNo, 
          postal = bwl.Postal, 
          city = bwl.City, 
          country = bwl.Country, 
          latitudetxt = bwl.Latitude == "" ? "Location Unknown" : "View Map Location", 
          latitude = bwl.Latitude, 
          longitude = bwl.Longitude, 
          date = bwl.ReceivedDate 
         }); 
Problemi correlati