AutoMapper-project of nested objects, where the internal object is nullified with an error

I use AutoMapper to create the following structure

public class OuterSource { .... public Guid? InnerId { get; set } public InnerSource Inner { get; set; } } public class InnerSource { public Guid Id { get; set; } public DateTime Date { get; set; } } public class OuterDest { .... public InnerDest Inner { get; set; } } public class InnerDest { public Guid Id { get; set; } public DateTime Date { get; set; } } var result = AutoMapper.Project<OuterSource, OuterDest>(query); 

As you can see, the Inner Object is NULL.

The projector works fine if the Inner object has a value, but if the internal object is NULL, EF will throw an exception as if it does not understand that InnerDest should actually be null.

 "The cast to value type 'Guid' failed because the materialized value is null. Either the result type generic parameter or the query must use a nullable type." 

Using

 var result = AutoMapper.Map<IEnumerable<OuterSource>, IEnumerable<OuterDest>>(query); 

really solves my problem, but obviously I would rather use a project.

Is there a good way around this, or I just can't use .Project for nested mappings with nullable internal objects?

+5
source share
2 answers

The problem is that your source object has fields with a null value, but the destination object does not. If the property is not null and you try to set it to null, you will get an exception. To fix this, you have 2 options. Or make fields in the target field with a null value

 public class OuterDest { public Guid? Id { get; set; } public DateTime Date { get; set; } } 

Or create a custom handler in your mapping to handle zeros and set default values โ€‹โ€‹for the corresponding fields.

0
source

What is your mapping configuration? You need to individually match the external outsource => outerdest and innersource => innerdest so that they can be understood.

0
source

Source: https://habr.com/ru/post/1206163/


All Articles