extract key-name determination facility · Eclarian/JSONAPI.NET@44fa79b · GitHub
Skip to content

Commit 44fa79b

Browse files
author
Chris Santero
committed
extract key-name determination facility
Figured this made more sense as an extension method.
1 parent 0a26101 commit 44fa79b

4 files changed

Lines changed: 54 additions & 19 deletions

File tree

JSONAPI.EntityFramework.Tests/EntityFrameworkMaterializerTests.cs renamed to JSONAPI.EntityFramework.Tests/DbContextExtensionsTests.cs

Lines changed: 4 additions & 18 deletions

JSONAPI.EntityFramework.Tests/JSONAPI.EntityFramework.Tests.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@
116116
<Compile Include="Acceptance\AcceptanceTestsBase.cs" />
117117
<Compile Include="Acceptance\SortingTests.cs" />
118118
<Compile Include="ActionFilters\AsynchronousEnumerationTransformerTests.cs" />
119-
<Compile Include="EntityFrameworkMaterializerTests.cs" />
119+
<Compile Include="DbContextExtensionsTests.cs" />
120120
<Compile Include="Helpers\TestDbAsyncEnumerable.cs" />
121121
<Compile Include="Helpers\WaitsUntilCancellationDbAsyncEnumerator.cs" />
122122
<Compile Include="Helpers\TestDbAsyncEnumerator.cs" />
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Data.Entity;
4+
using System.Data.Entity.Core.Objects;
5+
using System.Data.Entity.Infrastructure;
6+
using System.Linq;
7+
using System.Reflection;
8+
9+
namespace JSONAPI.EntityFramework
10+
{
11+
internal static class DbContextExtensions
12+
{
13+
internal static IEnumerable<string> GetKeyNames(this DbContext dbContext, Type type)
14+
{
15+
var openMethod = typeof(DbContextExtensions).GetMethod("GetKeyNamesFromGeneric", BindingFlags.NonPublic | BindingFlags.Static);
16+
var method = openMethod.MakeGenericMethod(type);
17+
try
18+
{
19+
return (IEnumerable<string>)method.Invoke(null, new object[] { dbContext });
20+
}
21+
catch (TargetInvocationException ex)
22+
{
23+
throw ex.InnerException;
24+
}
25+
}
26+
27+
// ReSharper disable once UnusedMember.Local
28+
private static IEnumerable<string> GetKeyNamesFromGeneric<T>(this DbContext dbContext) where T : class
29+
{
30+
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
31+
ObjectSet<T> objectSet;
32+
try
33+
{
34+
objectSet = objectContext.CreateObjectSet<T>();
35+
36+
}
37+
catch (InvalidOperationException e)
38+
{
39+
throw new ArgumentException(
40+
String.Format("The Type {0} was not found in the DbContext with Type {1}", typeof(T).Name, dbContext.GetType().Name),
41+
e
42+
);
43+
}
44+
return objectSet.EntitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
45+
}
46+
47+
}
48+
}

JSONAPI.EntityFramework/JSONAPI.EntityFramework.csproj

Lines changed: 1 addition & 0 deletions

0 commit comments

Comments
 (0)