47

我正在使用官方 MongoDB C# Drive v0.9.1.26831,但我想知道给定一个 POCO 类,是否有忽略某些属性的插入。

例如,我有以下课程:

public class GroceryList
{
    public string Name { get; set; }
    public FacebookList Owner { get; set; }
    public bool IsOwner { get; set; }
}

有没有办法让IsOwner在我插入 GroceryList 对象时不被插入?基本上,我从数据库中获取对象,然后在应用层中设置 IsOwner 属性,然后将其返回给控制器,然后将对象映射到视图模型。

希望我的问题有意义。谢谢!

4

5 回答 5

69

看起来 [BsonIgnore] 属性完成了这项工作。

public class GroceryList : MongoEntity<ObjectId>
{
    public FacebookList Owner { get; set; }
    [BsonIgnore]
    public bool IsOwner { get; set; }
}
于 2011-02-03T23:13:52.327 回答
23

或者,如果您出于某种原因不想使用该属性(例如,如果您不想MongoDB.Bson为您的 DTO 带来额外的依赖项),您可以执行以下操作:

BsonClassMap.RegisterClassMap<GroceryList>(cm =>
{
  cm.AutoMap();
  cm.UnmapMember(m => m.IsOwner);
});
于 2016-03-23T09:59:21.380 回答
19

您也可以使IsOwnerNullable 并添加[BsonIgnoreExtraElements]到整个班级:

[BsonIgnoreExtraElements]
public class GroceryList : MongoEntity<ObjectId>
{
    public FacebookList Owner { get; set; }
    public bool? IsOwner { get; set; }
}

null在序列化期间将忽略具有值的属性。但我认为[BsonIgnore]对你的情况会更好。

于 2011-02-04T08:35:30.913 回答
6

您可能应该想要结合 BsonIgnoreExtraElements 和 BsonIgnore 这两个属性。原因是尽管 BsonIgnore 不会向您的数据库插入“IsOwner”属性,但如果您的数据库中有包含此字段的“旧”实例,您将从功能中的模型中删除此字段或扩展您的“GroceryList” " 类并在数据库中使用你的新类将得到一个异常:

“元素‘IsOwner’不匹配类的任何字段或属性。”

另一种方法(而不是编辑模型类)是将“ Register Class Map ”与“ SetIgnoreExtraElements”和“UnmapMember”一起使用。

在您的情况下,只需在初始化驱动程序时添加此代码:

BsonClassMap.RegisterClassMap<UserModel>(cm =>
{
     cm.AutoMap();
     cm.SetIgnoreExtraElements(true);
     cm.UnmapMember(m => m.IsOwner);
});

您可以在以下位置阅读有关 Mongo 类映射的更多信息:

http://mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/mapping/

于 2017-06-29T06:17:37.613 回答
5

以防万一有人可能对另一种方式感兴趣。通过约定:

public class IgnoreSomePropertyConvention : ConventionBase, IMemberMapConvention
{
    public void Apply(BsonMemberMap memberMap)
    { // more checks will go here for the case above, e.g. type check
        if (memberMap.MemberName != "DoNotWantToSaveThis")
            memberMap.SetShouldSerializeMethod(o => false);
    }
}

然后您需要在应用启动期间注册一次此约定:

ConventionRegistry.Register("MyConventions", new ConventionPack { new IgnoreBaseIdConvention()  }, t => true);
于 2017-03-01T00:21:47.593 回答