[CSHARP-3358] Support serialization of C# 9 records Created: 25/Jan/21  Updated: 27/Oct/23  Resolved: 10/Nov/22

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

Type: Improvement Priority: Major - P3
Reporter: Robert Stam Assignee: James Kovacs
Resolution: Works as Designed Votes: 3
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

C# 9 introduced record types:

https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/exploration/records

These look like syntactic sugar for creating immutable types and we might already support serialization of records as a by product of our support for serialization of immutable types, but this needs to be thoroughly tested.



 Comments   
Comment by James Kovacs [ 10/Nov/22 ]

C#9 records are supported with our current serializers. If you encounter a problem when serializing records, please open a new issue with a self-contained repro.

Comment by James Kovacs [ 08/Nov/22 ]

I created the following simple repro using .NET 6 and the 2.18.0 driver:

using MongoDB.Bson;
using MongoDB.Driver;
 
var client = new MongoClient();
var db = client.GetDatabase("test");
var coll = db.GetCollection<Person>("people");
 
var person = new Person(Id: ObjectId.Empty, Name: "James");
coll.InsertOne(person);
Console.WriteLine(person);

The output of this program is:

Person { Id = 636adc7b016a268b90d29985, Name = James }

Based on this repro, it would seem that Id is being updated with the inserted id as expected without requiring annotation with [BsonId] nor other special technique.

If this is still a problem, please provide a self-contained repro of the issue so that we can investigate further.

Thank you!
James

Comment by Ben Zuill-Smith [ 06/Feb/22 ]

Note that you'll need to add support for Attributes. For example:

public record User(
    [BsonId] string Id,
    [BsonElement("firstName")] string FirstName,
);

Comment by Rodion Mostovoy [ 20/Aug/21 ]

Why unassigned? Records are very useful feature. Actually it's almost supported at the moment. The only one bug that I found is no inserted id returning. I had to use this hack to get it work:

```
var col = _db.GetCollection<BsonDocument>(collectionName);
var document = entity.ToBsonDocument();
document["_id"] = ObjectId.Empty;
await col.InsertOneAsync(document);
var insertedEntity = entity with

{ id = document["_id"].ToString()! }

;
return insertedEntity;
```
As a workaround you can just return an inserted id in InsertOneAsync (now it's void).

Should I create a separate issue for this case?

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