为引用MongoDB的最佳实践 [英] MongoDB best practice for referencing

查看:101
本文介绍了为引用MongoDB的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么用引用建模的最佳实践将根据给出的局面。我使用 MongoRepository 库。

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和postRepository是MongoRepository类型。

userRepository and postRepository are of MongoRepository type.

这是正确的方法来解决使用MongoDB中使用C#我的问题/ MVC(4)?

Is this the correct approach to solving my problem using MongoDB with C#/MVC(4)?

推荐答案

您可以使用DBREF对象,而不是用户对象。

You can use DBRef 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 DBRef Owner { get; set; }
    }    

然后,您可以:

    var mongo = new Mongo(config.BuildConfiguration());
    mongo.Connect();        
    var DB = mongo.GetDatabase(_dataBaseName)

    var post = new Post();
    post.Owner = new DBRef("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);

这篇关于为引用MongoDB的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆