forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbContextExtensions.cs
More file actions
57 lines (53 loc) · 1.93 KB
/
DbContextExtensions.cs
File metadata and controls
57 lines (53 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
namespace JSONAPI.EntityFramework
{
/// <summary>
/// Extensions on DbContext useful for JSONAPI.NET
/// </summary>
public static class DbContextExtensions
{
/// <summary>
/// Gets the ID key names for an entity type
/// </summary>
/// <param name="dbContext"></param>
/// <param name="type"></param>
/// <returns></returns>
public static IEnumerable<string> GetKeyNames(this DbContext dbContext, Type type)
{
var openMethod = typeof(DbContextExtensions).GetMethod("GetKeyNamesFromGeneric", BindingFlags.NonPublic | BindingFlags.Static);
var method = openMethod.MakeGenericMethod(type);
try
{
return (IEnumerable<string>)method.Invoke(null, new object[] { dbContext });
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
// ReSharper disable once UnusedMember.Local
private static IEnumerable<string> GetKeyNamesFromGeneric<T>(this DbContext dbContext) where T : class
{
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<T> objectSet;
try
{
objectSet = objectContext.CreateObjectSet<T>();
}
catch (InvalidOperationException e)
{
throw new ArgumentException(
String.Format("The Type {0} was not found in the DbContext with Type {1}", typeof(T).Name, dbContext.GetType().Name),
e
);
}
return objectSet.EntitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
}
}
}