c# - 选择 Cosmos DB 文档时展平对象
问题描述
我在 Cosmos DB 中有以下文档
{
"id": "c6c7a79a-3351-8be8-2700-b0c9414c1622",
"_rid": "mdRtAJiE1cEBAAAAAAAAAA==",
"_self": "dbs/mdRtAA==/colls/mdRtAJiE1cE=/docs/mdRtAJiE1cEBAAAAAAAAAA==/",
"_etag": "\"00000000-0000-0000-35f2-3baea11001d5\"",
"FedId": "1023157382",
"UniqueIdentifier": "00003089421",
"UniqueIdentifierNumeric": 3089421,
"Item": {
"LastUpdatedDate": "2019-07-08T02:36:20",
"OrderNumber": "2013282",
"QueueRank": 2
}
}
以及以下 C# 类
public class Item
{
public string FedId { get; set; }
public string UniqueIdentifier { get; set; }
public DateTime LastUpdatedDate { get; set; }
public string OrderNumber { get; set; }
public int QueueRank { get; set; }
}
使用 Cosmos SQL API,如何选择文档并将其映射到Item
类?
以下是我尝试过的:
var result = _client.CreateDocumentQuery<Item>(collectionLink, new SqlQuerySpec
{
QueryText = @"
SELECT c.FedId, c.UniqueIdentifier, i.*
FROM c JOIN i IN c.Item
WHERE
sie.FedId = '1023157382'
"
});
本质上,除了地图文档属性外,我还需要Item
将 Cosmos 文档中的属性展平。我期待的结果是:
Console.WriteLine(result.FedId); // return "1023157382"
Console.WriteLine(result.UniqueIdentifier); // return "00003089421"
Console.WriteLine(result.LastUpdatedDate); // return "2019-07-08T02:36:20"
Console.WriteLine(result.OrderNumber); // return "2013282"
Console.WriteLine(result.QueueRank); // return 2
我也尝试过使用连接查询,但似乎不适用于非数组属性。 https://github.com/Azure/azure-cosmos-dotnet-v2/blob/d17c0ca5be739a359d105cf4112443f65ca2cb72/samples/code-samples/Queries/Program.cs#L421-L435
解决方案
如果您没有数组属性,则不需要进行连接。你可以只使用c.Item.LastUpdatedDate
.
结果应如下所示:
var result = _client.CreateDocumentQuery<Item>(collectionLink, new SqlQuerySpec
{
QueryText = @"
SELECT c.FedId, c.UniqueIdentifier, c.Item.LastUpdatedDate, c.Item.OrderNumber, c.Item.QueueRank
WHERE
c.FedId = '1023157382'
"
});
另一方面,您也可以尝试使用 linq 提供程序。为您的顶级文档(例如MyDocument
)和它的项目部分创建一个类,并使用它select
来映射值。
会像这样工作:
var result = _client.CreateDocumentQuery<MyDocument>(collectionLink)
.Select(document => new Item{
FedId = document.FedId,
UniqueIdentifier = document.FedId,
LastUpdatedDate = document.Item.LastUpdatedDate,
OrderNumber = document.Item.OrderNumber,
QueueRank = document.Item.QueueRank
});
PS:SelectMany
一旦有了数组属性就使用,而不是编写 SQL 连接。
推荐阅读
- sql - 将 SQL 查询转换为 MDX - 具有 Group by 和 Count 函数
- r - 如何将前导数字标识符(不一定为零)添加到 r 中的字符串
- c# - iText 7 是否支持叙利亚语?
- google-sheets - 表单提交导致 Google 表格公式中的行跳过
- silverstripe-4 - 取消发布页面时出现 silverstripe 内部服务器错误
- php - [SQL Server]表附近的语法不正确
- css - 仅 CSS - 从自动转换到自动
- mysql - Insert same auto increment value to another column of same table
- javascript - 如何缓慢显示部分视图,而不显示:无?
- gmail-api - 修改邮件的Gmail-API问题(权限不足)c#