Skip to content

Commit 4e20fa8

Browse files
committed
Add test to show that RegisterType can be used instead of ctor.
1 parent 9843a4e commit 4e20fa8

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Text.Json;
6+
using System.Threading.Tasks;
7+
8+
using Xunit;
9+
10+
namespace LiteDB.Tests.Issues;
11+
12+
public class Issue2298_Tests
13+
{
14+
public struct Mass
15+
{
16+
public enum Units
17+
{ Pound, Kilogram }
18+
19+
public Mass(double value, Units unit)
20+
{ Value = value; Unit = unit; }
21+
22+
public double Value { get; init; }
23+
public Units Unit { get; init; }
24+
}
25+
26+
public class QuantityRange<T>
27+
{
28+
public QuantityRange(double min, double max, Enum unit)
29+
{ Min = min; Max = max; Unit = unit; }
30+
31+
public double Min { get; init; }
32+
public double Max { get; init; }
33+
public Enum Unit { get; init; }
34+
}
35+
36+
public static QuantityRange<Mass> MassRangeBuilder(BsonDocument document)
37+
{
38+
var doc = JsonDocument.Parse(document.ToString()).RootElement;
39+
var min = doc.GetProperty(nameof(QuantityRange<Mass>.Min)).GetDouble();
40+
var max = doc.GetProperty(nameof(QuantityRange<Mass>.Max)).GetDouble();
41+
var unit = Enum.Parse<Mass.Units>(doc.GetProperty(nameof(QuantityRange<Mass>.Unit)).GetString());
42+
43+
var restored = new QuantityRange<Mass>(min, max, unit);
44+
return restored;
45+
}
46+
47+
[Fact]
48+
public void We_Dont_Need_Ctor()
49+
{
50+
BsonMapper.Global.RegisterType<QuantityRange<Mass>>(
51+
serialize: (range) => new BsonDocument
52+
{
53+
{ nameof(QuantityRange<Mass>.Min), range.Min },
54+
{ nameof(QuantityRange<Mass>.Max), range.Max },
55+
{ nameof(QuantityRange<Mass>.Unit), range.Unit.ToString() }
56+
},
57+
deserialize: (document) => MassRangeBuilder(document as BsonDocument)
58+
);
59+
60+
var range = new QuantityRange<Mass>(100, 500, Mass.Units.Pound);
61+
var filename = "Demo.DB";
62+
var DB = new LiteDatabase(filename);
63+
var collection = DB.GetCollection<QuantityRange<Mass>>("DEMO");
64+
collection.Insert(range);
65+
var restored = collection.FindAll().First();
66+
}
67+
}

0 commit comments

Comments
 (0)