Skip to content

Commit d4e868f

Browse files
author
Chris Santero
committed
search base types for unregistered types
When trying to determine the resource type name for a type "A" that is not registered but is derived from another type "B" that is, then the model manager should return the resource type name for type "B". This is particularly useful when trying to serialize Entity Framework proxies.
1 parent 42392cd commit d4e868f

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

JSONAPI.Tests/Core/ModelManagerTests.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ private class CustomIdModel
2525
public string Data { get; set; }
2626
}
2727

28+
private class DerivedPost : Post
29+
{
30+
31+
}
32+
2833
[TestMethod]
2934
public void FindsIdNamedId()
3035
{
@@ -90,6 +95,21 @@ public void GetResourceTypeName_returns_correct_value_for_registered_types()
9095
Assert.AreEqual("user-groups", userGroupsKey);
9196
}
9297

98+
[TestMethod]
99+
public void GetResourceTypeNameForType_gets_name_for_closest_registered_base_type_for_unregistered_type()
100+
{
101+
// Arrange
102+
var pluralizationService = new PluralizationService();
103+
var mm = new ModelManager(pluralizationService);
104+
mm.RegisterResourceType(typeof(Post));
105+
106+
// Act
107+
var resourceTypeName = mm.GetResourceTypeNameForType(typeof(DerivedPost));
108+
109+
// Assert
110+
resourceTypeName.Should().Be("posts");
111+
}
112+
93113
[TestMethod]
94114
public void GetResourceTypeNameForType_fails_when_getting_unregistered_type()
95115
{

JSONAPI/Core/ModelManager.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,15 @@ public string GetResourceTypeNameForType(Type type)
136136
if (IsSerializedAsMany(type))
137137
type = GetElementType(type);
138138

139-
string resourceTypeName;
140-
if (_resourceTypeNamesByType.Value.TryGetValue(type, out resourceTypeName)) return resourceTypeName;
139+
var currentType = type;
140+
while (currentType != null && currentType != typeof(Object))
141+
{
142+
string resourceTypeName;
143+
if (_resourceTypeNamesByType.Value.TryGetValue(currentType, out resourceTypeName)) return resourceTypeName;
144+
145+
// This particular type wasn't registered, but maybe the base type was
146+
currentType = currentType.BaseType;
147+
}
141148

142149
throw new InvalidOperationException(String.Format("The type `{0}` was not registered.", type.FullName));
143150
}

0 commit comments

Comments
 (0)