我想知道在这种情况下,通过引用进行建模的最佳实践是什么.我正在使用MongoRepository个图书馆.

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; }
}

存储帖子时,我只希望引用所有者(用户)对象,而不是底层的整个对象.

目前我就是这样做的,不知道更好的方法...

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类型.

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

推荐答案

可以使用MongoDBRef对象而不是用户对象.

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; }
}    

然后你可以:

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);

Mongodb相关问答推荐

会话的Mongo-go驱动程序版本.Copy()

在对象mongodb的数组中查找元素

如何为具有相同名称的嵌套字段创建文本索引

lexik_jwt_authentication下无法识别的选项api_platform

MongoDB 使用 pymongo 收集 500K 文档的写入速度很差

MongoDB - 分组并找到前 N 个

在 MongoDB 中打开连接的 SocketTimeout

MongoDB聚合多条件

解析命令行时出错:unrecognized option --rest

如何使用 mongoose 从 MongoDb 获取数据?

如何更新 mongodb 文档以向数组添加新元素?

使用 nodejs/mongoose 部分更新子文档

MongoDB 批处理操作的最大大小是多少?

有没有办法将python对象直接存储在mongoDB中而不序列化它们

如何在 mongoDB 中聚合巨大的数组?

如何在 MongoDB Map-reduce 映射函数中使用变量

插入违反唯一索引的 MongoDB 文档时如何捕获错误?

MongoDB 在 mongoengine 中使用 OR 子句

如何在mongoose的嵌套填充中 Select 特定字段

Mongo 条件为key doesn't exist?