Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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);
12 changes: 9 additions & 3 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,9 +38,14 @@ 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
if (constructors.Count(c => c.GetCustomAttribute<MagicConstructorAttribute>() != null) > 1)
{
throw new MagicConstructorException("Only one magic constructor is allowed");
}

var magicConstructor = constructors.FirstOrDefault(c => c.GetCustomAttribute<MagicConstructorAttribute>() != null);
if (magicConstructor == null)
{
Constructor = constructors.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
}
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