使用BsonIgnore忽略Composite属性中的属性 [英] Ignoring Properties inside Composite Property with BsonIgnore

查看:329
本文介绍了使用BsonIgnore忽略Composite属性中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码使用BsonIgnore忽略class中的某些属性.但是它忽略了整个对象.

I uses the below to code to ignore some property inside a class using BsonIgnore. But it is ignoring the total object.

public class User
{
    public string Username { get; set; }
    public string Password { get; set; }

    [BsonIgnore,JsonProperty(PropertyName = "CreateDate")]
    public ICollection<Role> Roles { get; set; }
}

public class Role
{
    public int RoleId {get; set;}
    public string RoleName { get; set; }
    public DateTime CreateDate { get; set;}

} 

我有2个问题.

  1. 如何仅忽略类中的某些属性?我不应该在Role类中直接使用BsonIgnore.
  2. 如何忽略多个属性?如下所示.
  1. How to ignore only certain properties inside a class? I should not use BsonIgnore directly inside Role class.
  2. How to ignore multiple properties? Something like below.

代码:

[BsonIgnore,JsonProperty(PropertyName = "CreateDate")]
[BsonIgnore,JsonProperty(PropertyName = "RoleId")]
public ICollection<Role> Roles { get; set; }

推荐答案

有两种方法可让您定义序列化类的方式:使用属性或为您的类创建类映射您的初始化代码. 类映射是定义类和BSON文档之间映射的结构.它包含参与序列化的类的字段和属性的列表,并为每个字段定义了所需的序列化参数(例如BSON元素的名称,表示选项等).因此,在您的情况下,您可以执行以下操作:

There are two ways that let you define how you want serialize your classes: using attributes or creating a class map for your class in your initialization code. A class map is a structure that defines the mapping between a class and a BSON document. It contains a list of the fields and properties of the class that participate in serialization and for each one defines the required serialization parameters (e.g., the name of the BSON element, representation options, etc...). So, in your case you could do something like this:

  BsonClassMap.RegisterClassMap<Role>(cm =>
  {
     cm.AutoMap();// Automap the Role class
     cm.UnmapProperty(c => c.RoleId); //Ignore RoleId property
     cm.UnmapProperty(c => c.CreateDate);//Ignore CreateDate property
  });

您可以在以下链接.

这篇关于使用BsonIgnore忽略Composite属性中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆