首页 > 解决方案 > MongoDB C# 驱动程序:如何忽略 Insert 上的属性,但不在 .Lookup() 中

问题描述

我有以下模型用于反序列化数据库中的集合:

[BsonCollection("alerts")]
public class Alert
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }

    [BsonRepresentation(BsonType.ObjectId)]
    public string AlertTypeId { get; set; }

    [BsonRepresentation(BsonType.ObjectId)]
    public string Label Id { get; set; }

    public AlertType AlertType { get; set; }

    public Label Label { get; set; }
}

属性 AlertType 和 Label 仅用于在应用 .Lookup() 时将来自其他集合的对象反序列化为 Alert 对象。

所以我希望它们被忽略(插入、编辑等)。

我尝试添加属性 [BsonIgnore],但在应用 Lookup 时会引发错误:

'元素'AlertType' 与 BAS.Models.AlertSettings.AlertSetting 类的任何字段或属性都不匹配。

这意味着忽略发生在反序列化和序列化中。

这是一种我可以实现仅在插入或编辑时忽略属性的方法吗?

标签: c#mongodblinqdriverbson

解决方案


我将使用 2 个不同的类来表示集合中的文档,并使用一个来表示从聚合中查找的投影,因为这个模型似乎用于多种目的。


推荐阅读