开发者

C# class design issue for mongodb

I got a problem in C# class design for mongodb, suppose there two class:

public class Group
{
    public Group()
    {
        Users = new List<User>();
    }
    public ObjectId Id { get; set; }
    public List<User> Users { get; set; }
}

public class User
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

and there are two seperate collections corresponding to them in mongodb, the schema is like this:

Group:
{
    "_id" : ObjectId("4e7839d90a2248d934c182bd"),
    "Name" : "Group1",
    "Users" : [ 
        {"_id": ObjectId("4e7839d90a2248d934c154af"), "Name": "User1"}
      ]
}
User:
{
    "_id" : ObjectId("4e7839d90a2248d934c154af"),
    "Name" : "User1",
"Email": "some@some.com"
}

according to some Mongodb design principles, everytime when I want to display every users' na开发者_如何学Pythonme within a group, so I embed some user's fields in group collection, thus only single one query is needed, but when inserting a Group object, all fields in each User object will be inserted, for example above: the email also will be inserted, which destroy the initial schema and occupy more space. so how can I cut the User's email out when insert a Group object, do you guys have any good idea?


This because when denormalizing data you need to create separate class for each denormilized object. In your case for User within Group you need to create separate class like this one:

public class GroupUser
{
   public ObjectId Id {get;set;}

   public string Name {get;set;}
}

Then your Group class will looks like this:

public class Group
{
  public Group()
  {
    Users = new List<GroupUser>();
  }
  public ObjectId Id { get; set; }
  public List<GroupUser> Users { get; set; }
}

And when you inserting new Group you need to map data from regular user to denormalized GroupUser. So denormalization usual lead to a lot of mapping and extra classes. But it allow us to achieve high performance in data loading from a database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜