我正在尝试编写一个通用方法来将对象插入为嵌入式文档。下面的代码已经可以工作了,但是我需要创建一个可以放入存储库并从控制器调用的通用方法。我需要传入根 ID 和需要插入的子文档对象。
class Post
{
...
public IList<Comment> Comments { get; set; }
}
using (var db = Mongo.Create(session.ConnectionString()))
{
IMongoCollection<Post> _collection = db.GetCollection<Post>("Post");
var comment = new Comment();
comment.InjectFrom(commentViewModel.comment);
// Use below to add *NEW* embedded document
_collection.UpdateOne(
new { _id = commentViewModel.Id },
new { Comments = M.AddToSet(comment) }
);
}
例如,这是我用来检索文档的方法,我正在寻找类似于插入的东西:
// Controller
var session = new MongoSession();
var post = session.Single<Post>(c => c.Id == id);
//Repository
public T Single<T>(System.Linq.Expressions.Expression<Func<T, bool>> expression) where T : class, new()
{
T retval = default(T);
using (var db = Mongo.Create(_connectionString))
{
retval = db.GetCollection<T>().AsQueryable()
.Where(expression).SingleOrDefault();
}
return retval;
}
更新
请注意,调用:
_collection.UpdateOne(
new { _id = commentViewModel.Id },
new { Comments = M.AddToSet(comment) }
)
做我需要的,我只是希望能够将它作为一个通用调用(因为没有更好的词)这样的东西(工作版本除外):
//Controller
var session = new MongoSession();
session.AddSubDocument<>(new Post { Id = commentViewModel.Id }, new { Comments = M.AddToSet(comment) });
// Repository ==> NOT WORKING SAMPLE
public void AddSubDocument<X, U>(X matchDocument, U valueDocument)
{
using (var db = Mongo.Create(_connectionString))
{
db.GetCollection<X>().UpdateOne(matchDocument, valueDocument);
}
}
希望这更有意义。
谢谢你,迈克