여기 상황이 있습니다. 새 게시물을 삽입하고 삽입 후 게시물을 가져오고 잘 작동합니다. 그럼 내가 잘 작동하는 하나의 필드와 업데이 트를 변경합니다. 문제는 업데이트 후 동일한 게시물을 가져 오려고 할 때 발생합니다. 항상 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 업데이 트와 관련된 보내야 할 몇 가지 이유가 필요합니다. 여기 예가 있습니다 :
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 바이트 코드가 다를 것 같아요.