Strange behavior of MongoDB LINQ provider for fields called “id”

Deadly 提交于 2019-12-01 04:00:20

MongoDB requires that every document stored in the database have a field (at the root level) called "_id".

The C# driver assumes that any field in your class called "Id", "id" or "_id" is meant to be mapped to the special "_id" field. This is a convention, one that can be overridden. The C# driver doesn't know that your Result class isn't meant to be used as the root document of a collection, so it finds your "id" field and maps it to "_id" in the database.

One way you can override this is to change the name of the field in your class (as you discovered). What you can then also do is use the [BsonElement] attribute to map your C# field name (e.g. "idd") to whatever name is actually being used in the database (e.g. "id"). For example:

public class Result
{
    [BsonElement("id")]
    public int idd; // matches "id" in the database
    // other fields
}

Another alternative is to override the convention that finds the "Id" member of a class to suppress the default behavior of the C# driver for your Result class. You can do this by registering a new ConventionProfile for your Result class. For example:

var noIdConventions= new ConventionProfile();
noIdConventions.SetIdMemberConvention(new NamedIdMemberConvention()); // no names
BsonClassMap.RegisterConventions(noIdConventions, t => t == typeof(Result));

You must be sure to do this very early in your program, before your Result class gets mapped.

Alex

The problem is your POCO doesn't match your JSON

Your Twitter class has an ID and a class called results
Yet, your JSON just has results. That's where the problem lies.

So in reality, you're bypassing the Twitter class, and just creating an instance of Result

Your JSON should look something like:

{
  _id: ObjectId("50c9c8f3e0ae76405f7d2b5e"), 
  "results": { 
     "text":"@twitterapi  http://tinyurl.com/ctrefg",
     "to_user_id":396524,
     "to_user":"TwitterAPI",
     "from_user":"jkoum",
     "metadata":
     {
      "result_type":"popular",
      "recent_retweets": 109
     },
     "id":1478555574, 
     "from_user_id":1833773,
     "iso_language_code":"nl",
     "source":"<a href=\"http://twitter.com/\">twitter<\/a>",
     "profile_image_url":"http://s3.amazonaws.com/twitter_production/profile_images/118412707/2522215727_a5f07da155_b_normal.jpg",
     "created_at":"Wed, 08 Apr 2009 19:22:10 +0000",
     "since_id":0,
     "max_id":1480307926,
     "refresh_url":"?since_id=1480307926&q=%40twitterapi",
     "results_per_page":15,
     "next_page":"?page=2&max_id=1480307926&q=%40twitterapi",
     "completed_in":0.031704,
     "page":1,
     "query":"%40twitterapi"}
    }
}

Edit

Your results is actually an embedded document (in the case of your POCO model currently) so you should also mark Result.ID with [BsonId]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!