Created
August 22, 2020 08:37
-
-
Save ruxo/255a92ff2abea67f0ce941c5365dcf3a to your computer and use it in GitHub Desktop.
Sample of C# MongoDB with Immutable classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // reference MongoDB.Driver 2.11.0 | |
| using MongoDB.Bson.Serialization.Attributes; | |
| using MongoDB.Bson.Serialization.Conventions; | |
| using MongoDB.Driver; | |
| void Main() | |
| { | |
| var client = new MongoClient("mongodb://connection"); | |
| var collection = client.GetDatabase("test").GetCollection<Test>("test"); | |
| collection.InsertOne(new Test("key", 123, new TestX(123.45m))); | |
| collection.Find(t => t.Key == "key").Single().Dump(); | |
| } | |
| public sealed class Test { | |
| [BsonId] | |
| public string Key {get;} | |
| public long Offset {get;} | |
| public TestX Data {get;} | |
| public Test(string Key, long Offset, TestX Data) { | |
| this.Key = Key; | |
| this.Offset = Offset; | |
| this.Data = Data; | |
| } | |
| } | |
| public sealed class TestX { | |
| public decimal Value { get; } | |
| public TestX(decimal Value) { this.Value = Value; } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, MongoDB only serializes properties, no fields.