2
這是情況。我插入一個新的帖子,插入後我獲取帖子,它工作正常。然後我改變一個領域,並更新哪些工作正常。當我嘗試在更新後獲取相同的帖子時,就會出現問題。它總是返回null。C#MongoDb驅動程序問題更新失敗
public class Post
{
public string _id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
// insert a post
var post = new Post() {Title = "first post", Body = "my first post"};
var posts = _db.GetCollection("posts");
var document = post.ToDocument();
// inserts successfully!
posts.Insert(document);
// now get the post
var spec = new Document() {{"_id", document["_id"]}};
// post was found success
var persistedPost = posts.FindOne(spec).ToClass<Post>();
persistedPost.Body = "this post has been edited again!!";
var document2 = persistedPost.ToDocument();
// updates the record success although I don't want to pass the second parameter
posts.Update(document2,spec);
// displays that the post has been updated
foreach(var d in posts.FindAll().Documents)
{
Console.WriteLine(d["_id"]);
Console.WriteLine(d["Body"]);
}
// FAIL TO GET THE UPDATED POST. THIS ALWAYS RETURNS NULL ON FindOne call!
var updatedPost = posts.FindOne(new Document() {{"_id",document["_id"]}}).ToClass<Post>(); // this pulls back the old record with Body = my first post
Assert.AreEqual(updatedPost.Body,persistedPost.Body);
UPDATE:
我想我已經解決了這個問題,但這個問題是很奇怪的。看最後一行。
var updatedPost = posts.FindOne(new Document() {{"_id",document["_id"]}}).ToClass<Post>();
FindOne方法取決於文檔[「_ id」]的新文檔。不幸的是,這不起作用,出於某種原因,它需要您發送與更新命令後將獲得的persistedPost更新關聯的_id。這裏是例子:
var persistedPost = posts.FindOne(spec).ToClass<Post>();
persistedPost.Body = "this is edited";
var document2 = persistedPost.ToDocument();
posts.Update(document2,new Document() {{"_id",document["_id"]}});
var updatedPost = posts.FindOne(new Document(){{"_id",document2["_id"]}}).ToClass<Post>();
Console.WriteLine(updatedPost.Body);
看到,現在我發送document2 [「_ id」]而不是文檔字段。這似乎工作正常。我猜它爲每個「_id」字段生成的24字節代碼是不同的。