Skip to content

Commit

Permalink
Use HashCode package to combine primary key values
Browse files Browse the repository at this point in the history
  • Loading branch information
henkmollema committed Oct 23, 2024
1 parent f24e34c commit 3562d2f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
22 changes: 9 additions & 13 deletions src/Dommel/AutoMultiMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -693,31 +693,27 @@ internal static Delegate CreateMapDelegate<T1, T2, T3, T4, T5, T6, T7, TReturn>(
{
var includeTypes = new[]
{
typeof(T1),
typeof(T2),
typeof(T3),
typeof(T4),
typeof(T5),
typeof(T6),
typeof(T7)
}
typeof(T1),
typeof(T2),
typeof(T3),
typeof(T4),
typeof(T5),
typeof(T6),
typeof(T7)
}
.Where(t => t != typeof(DontMap))
.ToArray();

var targetProperties = typeof(T1).GetProperties();
var keyProperties = Resolvers.KeyProperties(typeof(T1)).Select(x => x.Property);

// Create unique number from two integers
// https://stackoverflow.com/a/14652569
static int Pair(int a, int b) => (int)(((a + b) * (a + b + 1) * 0.5) + b);

T1 GetOrAdd(T1 target)
{
// Populate the dictionary with cached items keyed by the hash code of
// the value of the primary key properties. This way multi mapping one-to-many
// relations don't produce multiple instances of the same parent record.
// Use paired hash codes of all key properties as cache key.
var cacheKey = keyProperties.Aggregate(0, (x, prop) => Pair(x, prop.GetValue(target)!.GetHashCode()));
var cacheKey = keyProperties.Aggregate(0, (x, prop) => HashCode.Combine(x, prop.GetValue(target)));
if (!results.TryGetValue(cacheKey, out var cachedItem))
{
cachedItem = target;
Expand Down
1 change: 1 addition & 0 deletions src/Dommel/Dommel.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Bcl.HashCode" Version="1.1.1" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>
</Project>

0 comments on commit 3562d2f

Please sign in to comment.