Linq to SQL - 在特定日期之前获取每个设备的最后一个已知历史记录条目

时间:2016-06-10 22:19:45

标签: c# sql sql-server linq

我有一个与此条目类似的问题:

how-do-i-query-sql-for-a-latest-record-date-for-each-user

......但我需要在Linq。

简而言之,那些不在乎阅读其他链接的人:

我有一个包含设备的历史记录表。我需要在给定日期之前为每个设备提供最新条目。所以我不需要一个特定的值,而是整行。

示例数据:

ID | DeviceId | State   | LastUpdatedDate
0  | 1        | Online  | 2016-01-05 10:23:45
1  | 2        | Offline | 2016-01-04 00:05:33
2  | 1        | Offline | 2016-01-01 06:13:25
3  | 1        | Online  | 2016-01-07 11:02:06
4  | 3        | Offline | 2016-01-03 18:00:25
5  | 4        | Online  | 2016-01-08 03:00:05
4  | 3        | Offline | 2016-01-08 04:27:21

所以,如果我想在2016-01-05之前拥有最后的已知状态,我希望得到以下结果:

ID    | DeviceId | State   | LastUpdatedDate
1     | 2        | Offline | 2016-01-04 00:05:33
2     | 1        | Offline | 2016-01-01 06:13:25
4     | 3        | Offline | 2016-01-03 18:00:25

NULL  | 4        | NULL    | NULL

不需要NULL条目,为了清楚起见,我只是添加了它。再一次,我需要在Linq中使用它。我可以使用foreach代码轻松完成此操作,但我不想对数据库进行700次调用。我希望这相当有效。

谢谢!

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

         string SERVICE_ACCOUNT_EMAIL = "MyAccount";
        var certificate = new X509Certificate2(@"XXX.p12", "notasecret", X509KeyStorageFlags.Exportable);
        ServiceAccountCredential credential = new ServiceAccountCredential(
          new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
          {
              Scopes = new[] { BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.Bigquery }

          }.FromCertificate(certificate));
        // Create the service.
        var service = new BigqueryService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "test"

        });

        Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest tabreq = new Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest();
        List<Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData> tabrows = new List<Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData>();
        Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData rd = new Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData();
        IDictionary<string, object> r = new Dictionary<string, object>();
        r.Add("Key", "Value");
        rd.Json = r;
        tabrows.Add(rd);
        tabreq.Rows = tabrows;
        tabreq.Kind = "bigquery#tableDataInsertAllRequest";
        service.Tabledata.InsertAll(tabreq, "xxx", "xxx", "xxx");