未知的鉴别器值 "SqlException",如何忽略动态类型的鉴别器

Unknown discriminator value "SqlException", How to ignore discriminator on dynamic type

我有如下模型:

[BsonIgnoreExtraElements]
public class MongoDbLogModel
{
    public string Level { get; set; }

    public string RenderedMessage { get; set; }

    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime? Timestamp { get; set; }

    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime UtcTimeStamp { get; set; }

    public dynamic Properties { get; set; }

    public dynamic Exception { get; set; }
}

这里是 JSON 模型:

{
  "_id": { "$oid": "61a8dadd1ab0e48d55b06626" },
  "Level": "Error",
  "UtcTimeStamp": { "$date": "2021-12-02T14:40:30.436Z" },
  "MessageTemplate": {...},
  "RenderedMessage": "",
  "Properties": {...},
  "Exception": {
    "_t": "SqlException",
    "HelpLink": null,
    "Source": "Core Microsoft SqlClient Data Provider",
    "HResult": -2146232060,
    "Message": "Invalid object name 'SystemControlLogs'.",
    "StackTrace": "   at Microsoft.Data.SqlClien",
    "Data": {...}
  }
}

这里是my code获取日志数据:

var logs = await _collection
                .Find(builder)
                .Skip(count * page)
                .Limit(count)
                .SortByDescending(entry => entry.Timestamp)
                .ToListAsync();

我在反序列化数据时遇到 Unknown discriminator value "SqlException" 异常。如果不为 Exception 属性 创建模型,有什么方法可以消除该异常? (我尝试了 BsonClassMap.RegisterClassMap<MongoDbLogModel>(); 但没有成功)。

您可能有一个在运行时检查的类型。我认为 MongoDB 驱动程序不支持动态(尽管尚未正式说明),推荐的解决方案是改用 BsonDocument。

Mixing Static and Dynamic Data - official documentation

我不确定 BsonDocument 是否适用于您,但这个解决方案是最简单的解决方案:

[BsonIgnoreExtraElements]
public class MongoDbLogModel
{
    public string Level { get; set; }

    public string RenderedMessage { get; set; }

    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime? Timestamp { get; set; }

    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime UtcTimeStamp { get; set; }
    
    //changed line
    [BsonElement("Properties")]
    public BsonDocument Properties { get; set; }
    
    //changed line
    [BsonElement("Exception")]
    public BsonDocument Exception { get; set; }
}

Working code

如果 BsonDocument 不符合您的目的。您必须实现自定义序列化程序。是这样的: Serialize dynamic data with mongodb