Skip to content

Commit 6bf83cc

Browse files
author
Chris Santero
committed
make GetKeyNames work recursively
1 parent e851748 commit 6bf83cc

2 files changed

Lines changed: 21 additions & 9 deletions

File tree

JSONAPI.EntityFramework.Tests/DbContextExtensionsTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ public void GetKeyNamesNotAnEntityTest()
8282
{
8383
// Act
8484
Action action = () => _context.GetKeyNames(typeof (NotAnEntity));
85-
action.ShouldThrow<ArgumentException>().Which.Message.Should().Be("The Type NotAnEntity was not found in the DbContext with Type TestDbContext");
85+
action.ShouldThrow<Exception>().Which.Message.Should().Be("Failed to identify the key names for NotAnEntity or any of its parent classes.");
8686
}
8787
}
8888
}

JSONAPI.EntityFramework/DbContextExtensions.cs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,28 @@ public static class DbContextExtensions
2121
/// <returns></returns>
2222
public static IEnumerable<string> GetKeyNames(this DbContext dbContext, Type type)
2323
{
24-
var openMethod = typeof(DbContextExtensions).GetMethod("GetKeyNamesFromGeneric", BindingFlags.Public | BindingFlags.Static);
25-
var method = openMethod.MakeGenericMethod(type);
26-
try
27-
{
28-
return (IEnumerable<string>)method.Invoke(null, new object[] { dbContext });
29-
}
30-
catch (TargetInvocationException ex)
24+
if (dbContext == null) throw new ArgumentNullException("dbContext");
25+
if (type == null) throw new ArgumentNullException("type");
26+
27+
var originalType = type;
28+
29+
while (type != null)
3130
{
32-
throw ex.InnerException;
31+
var openMethod = typeof(DbContextExtensions).GetMethod("GetKeyNamesFromGeneric", BindingFlags.Public | BindingFlags.Static);
32+
var method = openMethod.MakeGenericMethod(type);
33+
34+
try
35+
{
36+
return (IEnumerable<string>) method.Invoke(null, new object[] {dbContext});
37+
}
38+
catch (TargetInvocationException)
39+
{
40+
}
41+
42+
type = type.BaseType;
3343
}
44+
45+
throw new Exception(string.Format("Failed to identify the key names for {0} or any of its parent classes.", originalType.Name));
3446
}
3547

3648
/// <summary>

0 commit comments

Comments
 (0)