NullReferenceExceptions when Flattering

Jul 10, 2012 at 3:57 PM

Hi,

first of all thanks for this nice piece of code, I love the emit mapper ;)

When I use the flattering config and have null objects in the members chain on my source object I get NullReferenceExceptions.

Just change the test methode for testing the flattering config as follows:

 

[TestMethod]
		public void TestFlattering()
		{
			var source = new ModelObject
				{
					BaseDate = DateTime.Now,
					Sub = new ModelSubObject
					{
						ProperName = "Some name",
						SubSub = new ModelSubSubObject
						{
							IAmACoolProperty = "Cool daddy-o"
						}
					},
					Sub2 = new ModelSubObject
					{
						ProperName = "Sub 2 name"
					},
					SubWithExtraName = null /*new ModelSubObject
					{
						ProperName = "Some other name"
					}*/,
				};

			var mapper = ObjectMapperManager.DefaultInstance.GetMapper<ModelObject, ModelDto>(
				new FlatteringConfig()
			);
			var b = mapper.Map(source);

 

In an older post IGibson wrote that I could use the ConstructBy method to avoid NullReferenceExceptions. (In http://emitmapper.codeplex.com/discussions/231361)

But I don't now how.. can someone please explain me how I can avoid this NullReferenceExceptions?

Sep 22, 2012 at 10:18 AM

hi, have you solved the problem?

Sep 24, 2012 at 8:24 AM

No .. ;(

Jul 5, 2013 at 10:59 AM
Edited Jul 5, 2013 at 12:20 PM
What I do for flattening when an object can be null, I will check this with a lambda expression

Example config:
var config = new DefaultMapConfig().ConvertUsing<Thread, String>(t => t != null ? t.Name : null); 

Hope this helps