Ignoring Properties inside Composite Property with

2019-08-06 13:13发布

问题:

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

} 

I have 2 question.

  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.

Code:

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

回答1:

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

You can find more info about this subject in this link.