Olh*_*iuk 2 azure azure-cosmosdb
当我将对象向上插入cosmos db时,我想将对象类型保存为json对象的一部分。我尝试在实例化Cosmos Client实例时传递json序列化器,但是它不起作用。我仍然看不到文档中的对象类型。我正在尝试做的是:
public static readonly JsonSerializerSettings DefaultJsonSerializerSettings =
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
DateFormatString = "o",
DateFormatHandling = DateFormatHandling.IsoDateFormat,
};
var CosmosClient =
new DocumentClient(
new Uri(CosmosConfig.ServiceEndpoint),
CosmosConfig.AuthNKey,
DefaultJsonSerializerSettings,
connectionPolicySettings);
Run Code Online (Sandbox Code Playgroud)
还有其他没有先处理(将对象转换为jObject)的行为的方式吗?谢谢
更新:
我想要达到的目标就像文档中的下一个结构(自动序列化类型):
{
"$type" : "MyNamespace.Foo",
"Id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
"Name" : "Vasia"
}
Run Code Online (Sandbox Code Playgroud)
而不是像这样的当前(无类型):
{
"Id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
"Name" : "Vasia"
}
Run Code Online (Sandbox Code Playgroud)
使用Cosmos DB时,我经常让我的文档/类从类似于以下内容的抽象基类继承:
public abstract class DocModel
{
[JsonProperty(PropertyName = "$type")]
public virtual string Doctype => GetType().Name;
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这几乎可以为您提供所需的东西:
public class Cloud : DocModel
{
public string Name { get; set; }
}
public class Foo : DocModel
{
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
最终会变成
{
"$type":"Cloud",
"id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
"name" : "Vasia"
}
{
"$type":"Foo",
"id": "2560e1be-bf87-4720-a22e-b7e2c4c37f2e",
"name" : "Vasia2"
}
Run Code Online (Sandbox Code Playgroud)
您可以将Doctype属性更改为GetType()。FullName等,以获取名称空间等。
这也使您可以基于Doctype查询所有文档,例如:
var t = typeof(T).Name;
IDocumentQuery<T> query = _db.Client
.CreateDocumentQuery<T>(_db.CollectionUri, new FeedOptions { MaxItemCount = -1 })
.Where(predicate)
.Where(_ => _.Doctype == t)
.AsDocumentQuery();
Run Code Online (Sandbox Code Playgroud)
例如在通用存储库中使用。
| 归档时间: |
|
| 查看次数: |
1182 次 |
| 最近记录: |