Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Magic.IndexedDb/Exceptions/MagicConstructorException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Magic.IndexedDb.Exceptions;

public class MagicConstructorException(string message) : Exception(message);
17 changes: 13 additions & 4 deletions Magic.IndexedDb/Helpers/PropertyMappingCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Concurrent;
using System.Reflection;
using System.Text.Json.Serialization;
using Magic.IndexedDb.Exceptions;

namespace Magic.IndexedDb.Helpers;

Expand Down Expand Up @@ -37,12 +38,20 @@ public SearchPropEntry(Type type, Dictionary<string, MagicPropertyEntry> _proper
EnforcePascalCase = false;
}

// 🔥 Pick the best constructor: Prefer JsonConstructor, then fall back to a parameterized one, else fallback to parameterless
var jsonConstructor = constructors.FirstOrDefault(c => c.GetCustomAttribute<JsonConstructorAttribute>() != null);
if (jsonConstructor == null)
// 🔥 Pick the best constructor: Prefer MagicConstructor, then fall back to a parameterized one, else fallback to parameterless
try
{
Constructor = constructors.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
var magicConstructor = constructors.SingleOrDefault(c => c.GetCustomAttribute<MagicConstructorAttribute>() != null);
if (magicConstructor == null)
{
Constructor = constructors.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
}
}

catch (InvalidOperationException){
throw new MagicConstructorException("Only one magic constructor is allowed");
}

HasConstructorParameters = Constructor != null && Constructor.GetParameters().Length > 0;

// 🔥 Cache constructor parameter mappings
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Magic.IndexedDb.SchemaAnnotations;

/// <summary>
/// Sets the preferred constructor for serialization for MagicDB
/// </summary>
public class MagicConstructorAttribute : Attribute;
2 changes: 1 addition & 1 deletion TestBase/Models/Person.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class Nested

public class Person : MagicTableTool<Person>, IMagicTable<DbSets>
{
[JsonConstructor]
[MagicConstructor]
public Person()
{
DoNotMapTest2 = "Test";
Expand Down