Ignoring Properties inside Composite Property with BsonIgnore

好久不见. 提交于 2019-12-11 04:48:33

问题


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.



来源:https://stackoverflow.com/questions/29241788/ignoring-properties-inside-composite-property-with-bsonignore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!