简体   繁体   English

如何在 C# 中读取未知类型的 ComosDB 更改提要?

[英]How to read ComosDB change feed of unknown type in C#?

I have a single CosmosDB container that I would like to hook a change feed into.我有一个 CosmosDB 容器,我想将更改源挂钩到其中。 This container has a few different data structures stored inside of it, and normally would query by a data type tag.这个容器内部存储了一些不同的数据结构,通常会通过数据类型标签进行查询。 I would like to handle the change feed differently based on which object type is updated.我想根据更新的对象类型以不同的方式处理更改提要。 Is there a way to attach a query onto the change feed, or should I try and set the return data type as a Dictionary or dynamic?有没有办法将查询附加到更改提要上,或者我应该尝试将返回数据类型设置为字典还是动态?

I am not aware of any partial processing or querying in change feed processor library .我不知道更改提要处理器库中有任何部分处理或查询。

But you can do it in this way by just passing a JObject to the ChangesHandler :但是你可以通过路过一家做这样JObjectChangesHandler

var changesHandler = new Container.ChangesHandler<JObject>(async (IReadOnlyCollection<JObject> collection, CancellationToken token) =>
{
   /// First deserialize just to get the type of entity/class
   var typedObject = JsonConvert.DeserializeObject<TypedObject>(doc.ToString());

   if (typedObject.DataType == "yourdatatypetohandle1")
   {
       /// Do sth. with this item
       var entity1 = JsonConvert.DeserializeObject<EntityToHandle1>();
   }
   if (typedObject.DataType == "yourdatatypetohandle2")
   {
       /// Do sth. with this item
       var entity2 = JsonConvert.DeserializeObject<EntityToHandle2>();
   }
}

With some kind of model entities/classes:使用某种模型实体/类:

public class TypedObject 
{
    public virtual string DataType { get; set; }
}

public class EntityToHandle1 : TypedObject 
{
    public override string DataType { get; set; } = "yourdatatypetohandle1";
}

public class EntityToHandle1 : TypedObject 
{
    public override string DataType { get; set; } = "yourdatatypetohandle2";
}

Note that this solution is from a performance perspective not that perfect because 2x deserializing is not the best option.请注意,此解决方案从性能角度来看并不完美,因为 2x 反序列化不是最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM