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 : Entity { publis string Id { get; set; } public string Email { get; set; } public string Password { get; set; } } 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 User Owner { get; set; } }
When storing the Post I want only reference to Owner (User) object instead of whole object underlying.
Currently I'm doing it like this, not knowing of better way...
var post = new Post { Title = "Example title", Summary = "asd asd", Added = DateTime.Now, Owner = new User { Id = "someExistingUserId" } }; postRepository.Update(post); //Save
..
//Then to get the post var post = postRepository.GetById("previouslySavedPostId"); post.Owner = userRepository.GetById(post.Owner.Id); return post;
userRepository and postRepository are of MongoRepository type.
Is this the correct approach to solving my problem using MongoDB with C#/MVC(4)?
MongoDB applications use one of two methods to relate documents: Manual references save the _id field of one document in another document as a reference. Your application runs a second query to return the related data. These references are simple and sufficient for most use cases.
Sharded clusters in MongoDB are another way to potentially improve performance. Like replication, sharding is a way to distribute large data sets across multiple servers.
One of the primary benefits of creating Embedded Relationships in MongoDB is that the queries are executed faster than the referenced relationship. This relationship also improves performance, and results are obtained quickly. This is also true for large datasets.
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<User>(post.Owner);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With