2010-02-25 69 views
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字节代码是不同的。

回答

0

答案是不要依赖MongoDb生成的“_id”。只需使用您自己的唯一标识符如Guid或身份。

UPDATE:

我ToDocument方法把_id,你必须始终把_id为OID字符串。