Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-3845

Deserialize Select of anonymous types using default values for missing fields

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 2.15.0
    • Affects Version/s: None
    • Component/s: None
    • None

      Take this model:

      Unable to find source-code formatter for language: csharp. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      class A
      {
      	public string _id { get; set; }
      	public string ExistingA { get; set; }
      	public string ExistingB { get; set; }
      	[BsonDefaultValue(null)]
      	public string New { get; set; }
      }
      

      This data in the collection:

      {
      	"_id": "1",
      	"ExistingA": "Hello World",
      	"ExistingB": "Example"
      }
      

      And this LINQ query:

      Unable to find source-code formatter for language: csharp. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      collection.AsQueryable()
      	.Select(e => new
      	{
      		e._id,
      		e.ExistingA,
      		e.New
      	})
      	.First()
      

      This throws the "No matching creator found" exception because I can't specify default values for properties on anonymous types. I can't specify attributes on it etc. What I'm thinking is that maybe anonymous types should have assumed default values for all properties or otherwise ignored from the creator map processing.

      Anonymous types are an important piece of doing succinct LINQ select statements. I shouldn't need to declare a class manually (so I can add `BsonDefaultValue` attribute to the properties) just because the DB has less data than the model.

      Unfortunately this doesn't seem to be behaviour I can override on my end. I maintain MongoFramework and I can't really intercept the type and add default values myself. I mean, unless I'm going to write my own extension to LINQ Select, get the anonymous type out and manually register it myself before the driver even sees it. But that approach is likely error prone.

      So in summary, can the driver apply default values for all properties of anonymous types (as we can't set them ourselves).

            Assignee:
            robert@mongodb.com Robert Stam
            Reporter:
            james@turnersoftware.com.au James Turner
            Votes:
            1 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: