From 6f70b4bc900d2a565c7263f909668a4e6f9abd0e Mon Sep 17 00:00:00 2001 From: JKamsker Date: Mon, 2 Dec 2024 09:34:37 +0100 Subject: [PATCH] Add support for ValueTypes that consist only of Fields --- LiteDB.Tests/Issues/Issue2570_Tests.cs | 63 +++++++++++++++++++ .../Mapper/BsonMapper.GetEntityMapper.cs | 5 +- 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 LiteDB.Tests/Issues/Issue2570_Tests.cs diff --git a/LiteDB.Tests/Issues/Issue2570_Tests.cs b/LiteDB.Tests/Issues/Issue2570_Tests.cs new file mode 100644 index 000000000..1051f2bf6 --- /dev/null +++ b/LiteDB.Tests/Issues/Issue2570_Tests.cs @@ -0,0 +1,63 @@ +using FluentAssertions; +using Xunit; + +namespace LiteDB.Tests.Issues; + +public class Issue2570_Tests +{ + public class Person + { + public int Id { get; set; } + + public (string FirstName, string LastName) Name { get; set; } + } + + [Fact] + public void Issue2570_Tuples() + { + using (var db = new LiteDatabase(":memory:")) + { + var col = db.GetCollection("Person"); + + col.Insert(new Person { Name = ("John", "Doe") }); + col.Insert(new Person { Name = ("Joana", "Doe") }); + + var result = col.FindOne(x => x.Name.FirstName == "John"); + + result.Should().NotBeNull(); + result.Name.FirstName.Should().Be("John"); + result.Name.LastName.Should().Be("Doe"); + } + } + + public struct PersonData + { + public string FirstName; + public string LastName; + } + + public class PersonWithStruct + { + public int Id { get; set; } + + public PersonData Name { get; set; } + } + + [Fact] + public void Issue2570_Structs() + { + using (var db = new LiteDatabase(":memory:")) + { + var col = db.GetCollection("Person"); + + col.Insert(new PersonWithStruct { Name = new PersonData { FirstName = "John", LastName = "Doe" } }); + col.Insert(new PersonWithStruct { Name = new PersonData { FirstName = "Joana", LastName = "Doe" } }); + + var result = col.FindOne(x => x.Name.FirstName == "John"); + + result.Should().NotBeNull(); + result.Name.FirstName.Should().Be("John"); + result.Name.LastName.Should().Be("Doe"); + } + } +} \ No newline at end of file diff --git a/LiteDB/Client/Mapper/BsonMapper.GetEntityMapper.cs b/LiteDB/Client/Mapper/BsonMapper.GetEntityMapper.cs index f33f23970..96e0b083e 100644 --- a/LiteDB/Client/Mapper/BsonMapper.GetEntityMapper.cs +++ b/LiteDB/Client/Mapper/BsonMapper.GetEntityMapper.cs @@ -153,7 +153,10 @@ protected virtual IEnumerable GetTypeMembers(Type type) .Where(x => x.CanRead && x.GetIndexParameters().Length == 0) .Select(x => x as MemberInfo)); - if (this.IncludeFields) + var shouldIncludeFields = members.Count == 0 + && type.GetTypeInfo().IsValueType; + + if (shouldIncludeFields || this.IncludeFields) { members.AddRange(type.GetFields(flags).Where(x => !x.Name.EndsWith("k__BackingField") && x.IsStatic == false) .Select(x => x as MemberInfo));