From 573518c1677fa8ae9c8ca03f380e34296985f0ec Mon Sep 17 00:00:00 2001 From: Demis Bellot Date: Sun, 22 Apr 2018 00:57:24 -0400 Subject: [PATCH] Add MergeIntoObjectDictionary with test --- src/ServiceStack.Text/PlatformExtensions.cs | 14 +++++++++-- .../AutoMappingObjectDictionaryTests.cs | 25 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/ServiceStack.Text/PlatformExtensions.cs b/src/ServiceStack.Text/PlatformExtensions.cs index da76879c4..d8509f86a 100644 --- a/src/ServiceStack.Text/PlatformExtensions.cs +++ b/src/ServiceStack.Text/PlatformExtensions.cs @@ -660,8 +660,7 @@ public static Dictionary ToObjectDictionary(this object obj) var type = obj.GetType(); - ObjectDictionaryDefinition def; - if (!toObjectMapCache.TryGetValue(type, out def)) + if (!toObjectMapCache.TryGetValue(type, out var def)) toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type); var dict = new Dictionary(); @@ -776,5 +775,16 @@ public static Dictionary ToSafePartialObjectDictionary(this T } return to; } + + public static Dictionary MergeIntoObjectDictionary(this object obj, params object[] sources) + { + var to = obj.ToObjectDictionary(); + foreach (var source in sources) + foreach (var entry in source.ToObjectDictionary()) + { + to[entry.Key] = entry.Value; + } + return to; + } } } \ No newline at end of file diff --git a/tests/ServiceStack.Text.Tests/AutoMappingObjectDictionaryTests.cs b/tests/ServiceStack.Text.Tests/AutoMappingObjectDictionaryTests.cs index 89a2cbe49..b186a49ad 100644 --- a/tests/ServiceStack.Text.Tests/AutoMappingObjectDictionaryTests.cs +++ b/tests/ServiceStack.Text.Tests/AutoMappingObjectDictionaryTests.cs @@ -127,5 +127,30 @@ public void Can_convert_from_ObjectDictionary_into_AutoQuery_DTO() Assert.That(request.Meta, Is.EquivalentTo(new Dictionary {{"foo", "bar"}})); } + public class Employee + { + public string FirstName { get; set; } + public string LastName { get; set; } + public string DisplayName { get; set; } + } + + [Test] + public void Can_create_new_object_from_merged_objects() + { + var customer = new User { FirstName = "John", LastName = "Doe" }; + var map = customer.MergeIntoObjectDictionary(new {Initial = "Z"}); + map["DisplayName"] = map["FirstName"] + " " + map["Initial"] + " " + map["LastName"]; + var employee = map.FromObjectDictionary(); + + Dictionary MergeObjects(params object[] sources) { + var to = new Dictionary(); + sources.Each(x => x.ToObjectDictionary().Each(entry => to[entry.Key] = entry.Value)); + return to; + } + + Assert.That(employee.DisplayName, Is.EqualTo("John Z Doe")); + } + } + } \ No newline at end of file