Skip to content

Commit

Permalink
Support abstract record
Browse files Browse the repository at this point in the history
  • Loading branch information
glucaci committed Jul 10, 2024
1 parent 0db6a38 commit 2204d79
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
23 changes: 23 additions & 0 deletions src/Context.Tests/ImmutableConventionWithRecordsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<MongoResource>
{
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<T>(MongoDbContextData context, T input) where T : class
Expand Down
15 changes: 12 additions & 3 deletions src/Context/ImmutableConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
{
Expand All @@ -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(
Expand All @@ -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)
Expand Down

0 comments on commit 2204d79

Please sign in to comment.