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

Commit a0e4491

Browse files
committed
Add fix for AutoMapping null complex types
1 parent a49f9f6 commit a0e4491

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

src/ServiceStack.Text/AutoMappingUtils.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -734,8 +734,11 @@ public static PropertyGetterDelegate CreateTypeConverter(Type fromType, Type toT
734734
}
735735
else
736736
{
737-
return fromValue =>
737+
return fromValue =>
738738
{
739+
if (fromValue == null)
740+
return fromValue;
741+
739742
var toValue = toType.CreateInstance();
740743
toValue.PopulateWith(fromValue);
741744
return toValue;

tests/ServiceStack.Text.Tests/AutoMappingTests.cs

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,8 @@ public bool MatchesUsers(IEnumerable<User> u1s, IEnumerable<User> u2s)
408408
[Test]
409409
public void Does_convert_models_with_collections()
410410
{
411-
var from = new ModelWithEnumerable {
411+
var from = new ModelWithEnumerable
412+
{
412413
Collection = new[] {
413414
new User { FirstName = "First1", LastName = "Last1", Car = new Car { Name = "Car1", Age = 1} },
414415
new User { FirstName = "First2", LastName = "Last2", Car = new Car { Name = "Car2", Age = 2} },
@@ -437,5 +438,45 @@ public void Does_convert_models_with_collections()
437438
Assert.That(MatchesUsers(hashset, from.Collection.ConvertTo<User[]>()));
438439
Assert.That(MatchesUsers(hashset, from.Collection.ConvertTo<HashSet<User>>()));
439440
}
441+
442+
443+
public class Customer
444+
{
445+
public CompanyInfo CompanyInfo { get; set; }
446+
// other properties
447+
}
448+
449+
public class CustomerDto
450+
{
451+
public CompanyInfoDto CompanyInfo { get; set; }
452+
}
453+
454+
public class CompanyInfo
455+
{
456+
public int Id { get; set; }
457+
public string ITN { get; set; }
458+
}
459+
460+
public class CompanyInfoDto
461+
{
462+
public int Id { get; set; }
463+
public string ITN { get; set; }
464+
}
465+
466+
[Test]
467+
public void Does_retain_null_properties()
468+
{
469+
var user = new User { FirstName = "Foo" };
470+
var userDto = user.ConvertTo<UserFields>();
471+
472+
Assert.That(userDto.FirstName, Is.EqualTo("Foo"));
473+
Assert.That(userDto.LastName, Is.Null);
474+
Assert.That(userDto.Car, Is.Null);
475+
476+
var customer = new Customer { CompanyInfo = null };
477+
var dto = customer.ConvertTo<CustomerDto>();
478+
479+
Assert.That(dto.CompanyInfo, Is.Null);
480+
}
440481
}
441482
}

0 commit comments

Comments
 (0)