MongoDB best practice for referencing

后端 未结 2 1589
忘掉有多难
忘掉有多难 2020-12-08 11:05

I\'m wondering what the best practice for modelling by using references would be given situation under. I\'m using MongoRepository library.

public class User         


        
2条回答
  •  一整个雨季
    2020-12-08 11:17

    You can use MongoDBRef object instead of User object.

    public class Post : Entity
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Summary { get; set; }
        public DateTime Added { get; set; }
        public MongoDBRef Owner { get; set; }
    }    
    

    Then you can:

    var mongo = new Mongo(config.BuildConfiguration());
    mongo.Connect();        
    var DB = mongo.GetDatabase(_dataBaseName)
    
    var post = new Post();
    post.Owner = new MongoDBRef("User", userId); // First parameter is a mongoDB collection name and second is object id
    // To fetch object referenced by DBRef you should do following
    var owner = DB.FollowReference(post.Owner);
    

提交回复
热议问题