首页 文章

MongoDB C#驱动程序:忽略插入时的属性

提问于
浏览
30

我正在使用官方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; }
}

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

希望我的问题有道理 . 谢谢!

5 回答

  • 9

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

    public class GroceryList : MongoEntity<ObjectId>
    {
        public FacebookList Owner { get; set; }
        [BsonIgnore]
        public bool IsOwner { get; set; }
    }
    
  • 44

    你也可以使IsOwner为Nullable并将[BsonIgnoreExtraElements]添加到hole类:

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

    在诽谤期间,将忽略具有空值的 property . 但我认为[BsonIgnore]会更适合你的情况 .

  • 3

    或者,如果您不想将 MongoDB.Bson 的额外依赖性带到您的DTO,您可以执行以下操作:

    BsonClassMap.RegisterClassMap<GroceryList>(cm =>
    {
      cm.AutoMap();
      cm.UnmapMember(m => m.IsOwner);
    });
    
  • 14

    你应该想要 combine the two attributes BsonIgnoreExtraElements and BsonIgnore . 原因是虽然BsonIgnore不会将"IsOwner"属性插入到您的数据库中,但如果您的数据库中包含此字段的"old"实例,您将从该模型中删除该字段中的这些字段或扩展您的"GroceryList"类并使用您的新DB中的类将获得异常:

    “元素'IsOwner'与类的任何字段或属性都不匹配 . ”

    另一种方式(而不是编辑模型类)是使用“ Register Class Map " with " SetIgnoreExtraElements" and "UnmapMember" together.

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

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

    您可以在以下位置阅读有关Mongo Class Mapping的更多信息:

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

  • 2

    以防万一有人可能对另一种方式感兴趣 . 通过惯例:

    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);
        }
    }
    

    然后你需要在app启动期间注册一次这个约定:

    ConventionRegistry.Register("MyConventions", new ConventionPack { new IgnoreBaseIdConvention()  }, t => true);
    

相关问题