From 2204d79bc6f36f2a79ad12d81a225d257d6c6b0b Mon Sep 17 00:00:00 2001 From: glucaci Date: Wed, 10 Jul 2024 16:24:37 +0200 Subject: [PATCH] Support abstract record --- .../ImmutableConventionWithRecordsTests.cs | 23 +++++++++++++++++++ src/Context/ImmutableConvention.cs | 15 +++++++++--- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/Context.Tests/ImmutableConventionWithRecordsTests.cs b/src/Context.Tests/ImmutableConventionWithRecordsTests.cs index c9fc80f..7b9c695 100644 --- a/src/Context.Tests/ImmutableConventionWithRecordsTests.cs +++ b/src/Context.Tests/ImmutableConventionWithRecordsTests.cs @@ -111,7 +111,30 @@ public async Task ApplyConvention_SerializeSuccessful() public record A(B Foo, string BarFoo); public record B(string Bar); + } + + public class AbstractRecordCase : IClassFixture + { + private readonly MongoDbContextData _context; + + public AbstractRecordCase(MongoResource mongoResource) + { + _context = CreateContext(mongoResource); + } + + [Fact] + public async Task ApplyConvention_SerializeSuccessful() + { + // Arrange, Act and Assert + await InsertAndFind(_context, new B("foo")); + } + + public abstract record A(string Foo) + { + public string? Bar { get; set; } + } + public record B(string Foo) : A(Foo); } private static async Task InsertAndFind(MongoDbContextData context, T input) where T : class diff --git a/src/Context/ImmutableConvention.cs b/src/Context/ImmutableConvention.cs index c63951b..290f3d6 100644 --- a/src/Context/ImmutableConvention.cs +++ b/src/Context/ImmutableConvention.cs @@ -36,7 +36,7 @@ public void Apply(BsonClassMap classMap) .ToList(); var mappingProperties = properties - .Where(p => IsReadOnlyProperty(classMap, p) || IsInitOnlyProperty(p)) + .Where(p => IsReadOnlyProperty(classMap, p) || IsInitOnlyProperty(classMap, p)) .ToList(); foreach (PropertyInfo property in mappingProperties) @@ -140,7 +140,9 @@ private static bool IsReadOnlyProperty( return true; } - private bool IsInitOnlyProperty(PropertyInfo property) + private bool IsInitOnlyProperty( + BsonClassMap classMap, + PropertyInfo property) { if (!property.CanWrite) { @@ -153,7 +155,7 @@ private bool IsInitOnlyProperty(PropertyInfo property) var containsInit = setModifiers?.Any(m => m.FullName == _externalInitTypeName); - return containsInit ?? false; + return containsInit.GetValueOrDefault(false) && !IsBaseTypeProperty(classMap, property); } private static bool IsBaseTypeProperty( @@ -163,6 +165,13 @@ private static bool IsBaseTypeProperty( return getMethodInfo.GetBaseDefinition().DeclaringType != classMap.ClassType; } + private static bool IsBaseTypeProperty( + BsonClassMap classMap, + PropertyInfo propertyInfo) + { + return propertyInfo.DeclaringType != classMap.ClassType; + } + private static bool IsOverrideProperty( BsonClassMap classMap, MethodInfo getMethodInfo)