MongoDB将注释保存到嵌套数组
我对C#和MongoDB都是新手,在使用在线存储库模式将项目插入/更新/保存到嵌套数组中时遇到了一些问题()。下面是一些代码: 型号:MongoDB将注释保存到嵌套数组,mongodb,mongodb-.net-driver,Mongodb,Mongodb .net Driver,我对C#和MongoDB都是新手,在使用在线存储库模式将项目插入/更新/保存到嵌套数组中时遇到了一些问题()。下面是一些代码: 型号: public class BlogModel { [BsonId] public ObjectId Id { get; set; } public DateTime Date { get; set; } [Required] public string Title { get; set; } [Required]
public class BlogModel
{
[BsonId]
public ObjectId Id { get; set; }
public DateTime Date { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Body { get; set; }
public string Author { get; set; }
public IList<CommentModel> Comments { get; set; }
}
public class CommentModel
{
[BsonId]
public ObjectId Id { get; set; }
public DateTime Date { get; set; }
public string Author { get; set; }
[Required]
public string Body { get; set; }
}
公共类博客模型
{
[BsonId]
公共对象Id{get;set;}
公共日期时间日期{get;set;}
[必需]
公共字符串标题{get;set;}
[必需]
公共字符串体{get;set;}
公共字符串作者{get;set;}
公共IList注释{get;set;}
}
公共类评论模型
{
[BsonId]
公共对象Id{get;set;}
公共日期时间日期{get;set;}
公共字符串作者{get;set;}
[必需]
公共字符串体{get;set;}
}
以及存储库模式:
public void Add<T>(T item) where T : class, new()
{
_db.GetCollection<T>().Save(item);
}
public void Add<T>(IEnumerable<T> items) where T : class, new()
{
foreach (T item in items)
{
Add(item);
}
}
public void Add(T项),其中T:class,new()
{
_db.GetCollection().Save(项);
}
public void Add(IEnumerable items),其中T:class,new()
{
foreach(项目中的T项目)
{
增加(项目);
}
}
如何使用“add”类向嵌套数组添加注释?使用此存储库模式,将有四个步骤:
var myRepository = new Repository<BlogModel>();
var myDocument = myRepository.Find(some_id); // retrieve BlogModel document to update
myDocument.Comments.Add(some_new_comments); // add to IList
myRepository.Add(myDocument); // save changes to the document back to the repository
var myRepository=newrepository();
var myDocument=myRepository.Find(some_id);//检索要更新的BlogModel文档
myDocument.Comments.Add(一些新的注释);//添加到IList
myRepository.Add(myDocument);//将对文档的更改保存回存储库
请注意,由于addrepository方法使用C#Driver Save方法,因此它实际上具有以下功能。在这种情况下,您不会有CommentModel存储库,因为它的功能就像嵌入在BlogModel文档中的文档数组。谢谢dbaseman。您认为将更新类添加到我的存储库会更好吗?允许我做一些像
public void AddComment(ObjectId postId,Comment Comment){{u posts.Collection.Update(Query.EQ(“'u id”,id),Update.PushWrapped(“Comments”,Comment));}
@user1392537是的,我想这是有意义的。不过,我不确定在不“打破”通用存储库模式的情况下如何做到这一点。我猜只是子类存储库还是使用扩展方法?