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

Deserialize Select of anonymous types using default values for missing fields

    XMLWordPrintableJSON

Details

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: Unknown Unknown
    • 2.15.0
    • None
    • None
    • None

    Description

      Take this model:

      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:

      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).

      Attachments

        Activity

          People

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

            Dates

              Created:
              Updated:
              Resolved: