[CSHARP-3411] Ctors with Readonly Setters should just work. Created: 06/Feb/21  Updated: 09/Feb/21  Resolved: 09/Feb/21

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.11.6
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Tristen Fielding Assignee: Dmitry Lukyanov (Inactive)
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 10 Pro


Issue Links:
Duplicate
duplicates CSHARP-3240 ImmutableTypeClassMapConvention is ig... Closed

 Description   

The following simple class should be able to serialize and deserialize to the database without modification.

public class Sample
    {
        public Sample(DateTime dateTime, double value)
        {
            DateTime = dateTime;
            Value = value;
        }
        
        public DayOfWeek Day => DateTime.DayOfWeek;
        public int Hour => DateTime.TimeOfDay.Hours;
 
        public DateTime DateTime { get; }
        public double Value { get; }
    }

It is very clear the intent of this class. We have tried using [BsonConstructor] with no success either. We shouldn't be forced to use private setters to make this work. Private setters are very different than readonly setters, in both cases serialization and deserialization should just work.



 Comments   
Comment by Dmitry Lukyanov (Inactive) [ 09/Feb/21 ]

Hello aaron.treweek@vba.vic.gov.au , thanks for your report, we already fixed this issue and will release this in the next minor release, so please check it after that.

Also, be aware that a root database document also contains "_id" field which is not presented in your class. So, if your class represents a root db document, you should add "_id" field like:

public class Sample
{
   public Sample(int id, DateTime dateTime, double value)
   {
       Id = id;
       DateTime = dateTime;
       Value = value;
   }      
   public DayOfWeek Day => DateTime.DayOfWeek;
   public int Hour => DateTime.TimeOfDay.Hours;
   
   public int Id { get; }   
   public DateTime DateTime { get; }
   public double Value { get; }
}

if it is not the root document the Id is not needed.

Generated at Wed Feb 07 21:45:13 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.