2012-11-06 10 views
5

Mam dane z danymi view i muszę pobrać dane tylko z ostatnich 7 dni. Wiem, że istnieje funkcja dla tego, jeśli używałem kwerendy sql. ale używam Linq.Pobieranie danych z bazy danych w ciągu ostatnich 7 dni przy użyciu linq

tutaj jest mój kod:

   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); 
       } 

może ktoś mi powiedzieć jak to zrobić w Linq?

Odpowiedz

8

Możesz użyć numeru DateTime.Now.AddDays(-7), aby uzyskać rekord siedem dni starszy od bieżącej daty. Lub możesz użyć Datime.Today.AddDays (-7), jeśli chcesz część czasu i zacząć od po 12 PM.

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

myślę, że nie można używać DateTime.Now.AddDays (-1) wewnątrz LINQ do jednostki – Uriil

+0

lub 'DateTime.Today.AddDays (-7)', jeśli nie chcesz filtrować według czasu –

+0

@Adil Czy to zapytanie działa z datetime ?? –

1

Spróbuj tego:

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 
         }); 
Powiązane problemy