Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 573518c

Browse files
committed
Add MergeIntoObjectDictionary with test
1 parent 3ec23a3 commit 573518c

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/ServiceStack.Text/PlatformExtensions.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -660,8 +660,7 @@ public static Dictionary<string, object> ToObjectDictionary(this object obj)
660660

661661
var type = obj.GetType();
662662

663-
ObjectDictionaryDefinition def;
664-
if (!toObjectMapCache.TryGetValue(type, out def))
663+
if (!toObjectMapCache.TryGetValue(type, out var def))
665664
toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type);
666665

667666
var dict = new Dictionary<string, object>();
@@ -776,5 +775,16 @@ public static Dictionary<string, object> ToSafePartialObjectDictionary<T>(this T
776775
}
777776
return to;
778777
}
778+
779+
public static Dictionary<string, object> MergeIntoObjectDictionary(this object obj, params object[] sources)
780+
{
781+
var to = obj.ToObjectDictionary();
782+
foreach (var source in sources)
783+
foreach (var entry in source.ToObjectDictionary())
784+
{
785+
to[entry.Key] = entry.Value;
786+
}
787+
return to;
788+
}
779789
}
780790
}

tests/ServiceStack.Text.Tests/AutoMappingObjectDictionaryTests.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,5 +127,30 @@ public void Can_convert_from_ObjectDictionary_into_AutoQuery_DTO()
127127
Assert.That(request.Meta, Is.EquivalentTo(new Dictionary<string, object> {{"foo", "bar"}}));
128128
}
129129

130+
public class Employee
131+
{
132+
public string FirstName { get; set; }
133+
public string LastName { get; set; }
134+
public string DisplayName { get; set; }
135+
}
136+
137+
[Test]
138+
public void Can_create_new_object_from_merged_objects()
139+
{
140+
var customer = new User { FirstName = "John", LastName = "Doe" };
141+
var map = customer.MergeIntoObjectDictionary(new {Initial = "Z"});
142+
map["DisplayName"] = map["FirstName"] + " " + map["Initial"] + " " + map["LastName"];
143+
var employee = map.FromObjectDictionary<Employee>();
144+
145+
Dictionary<string,object> MergeObjects(params object[] sources) {
146+
var to = new Dictionary<string, object>();
147+
sources.Each(x => x.ToObjectDictionary().Each(entry => to[entry.Key] = entry.Value));
148+
return to;
149+
}
150+
151+
Assert.That(employee.DisplayName, Is.EqualTo("John Z Doe"));
152+
}
153+
130154
}
155+
131156
}

0 commit comments

Comments
 (0)