TinyMapper / TinyMapper

A quick object-object mapper for .NET
http://tinymapper.net
MIT License
691 stars 112 forks source link

Map from empty level 2 (and above) source #84

Closed m-fredsgaard closed 3 years ago

m-fredsgaard commented 4 years ago

Hi @GSerjo

Is it possible to support null-check for parent level properties in the MapClass method generated in the dynamic mapper:

This is the MapClass pseudo method, as it would be generated right now:

protected override MappingWithConfigTests.Target1 MapClass(
  MappingWithConfigTests.Source3 obj0,
  MappingWithConfigTests.Target1 obj1)
{
  obj1.MyString = obj0.Name.get_CName();
  return obj1;
}

Could the following be possible instead:

protected override MappingWithConfigTests.Target1 MapClass(
  MappingWithConfigTests.Source3 obj0,
  MappingWithConfigTests.Target1 obj1)
{
  obj1.MyString = ((obj0.Name != null) ? obj0.Name.get_CName() : null);
  return obj1;
}

This would result in mapping a null value instead of throwing a NullReferenceException, which in my opinion, is a correct mapping behavior.

I have looked into the ILGenerator implementation, but I simply can't figure out, how and where to emit the commands.

What is your opinion on this approach and can you help me accomplish this?

I have added a unit test (in this PR), that fails right now, but when the proposed change above is done, it should succeed

nzaugg commented 4 years ago

I think that's a good idea, and I agree that it's more correct to set the value to null than to throw a NRE.