2012-11-06 8 views
5

Tôi có view với dữ liệu và tôi chỉ cần truy xuất dữ liệu từ 7 ngày qua. Tôi biết có một chức năng cho điều này nếu tôi đã sử dụng truy vấn sql. nhưng tôi đang sử dụng LINQ.Truy xuất dữ liệu từ cơ sở dữ liệu trong vòng 7 ngày qua bằng linq

đây là mã của tôi:

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

bất cứ ai có thể cho tôi biết làm thế nào tôi làm điều này trong LINQ?

Trả lời

8

Bạn có thể sử dụng DateTime.Now.AddDays(-7) để nhận bản ghi 7 ngày trước ngày hiện tại. Hoặc bạn có thể sử dụng Datime.Today.AddDays (-7) nếu bạn muốn phần thời gian và bắt đầu từ sau 12 giờ tối.

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

Tôi nghĩ rằng bạn không thể sử dụng DateTime.Now.AddDays (-1) bên trong LINQ to Entity – Uriil

+0

Hoặc 'DateTime.Today.AddDays (-7) ', nếu bạn không muốn lọc theo thời gian –

+0

@Adil Truy vấn này có đang hoạt động với datetime không ?? –

1

Hãy thử điều này:

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