cezarypiatek / MappingGenerator

:arrows_counterclockwise: "AutoMapper" like, Roslyn based, code fix provider that allows to generate mapping code in design time.
https://marketplace.visualstudio.com/items?itemName=54748ff9-45fc-43c2-8ec5-cf7912bc3b84.mappinggenerator
MIT License
1.03k stars 120 forks source link

Set target null if source is null #80

Closed StillLearnin closed 5 years ago

StillLearnin commented 5 years ago

I would find it helpful if null checking code was generated along with the mapping code. Any thoughts on this?

Example:

public void Map(MyModel model, MyEntity entity)
{
    if (model == null)    //New code to generate
    {
        entity = null;
        return;
    }                    //End new code to generate
    entity.Prop1 = model.Prop1;
    entity.Prop2 = model.Prop2;
}

or

public MyEntity Map(MyModel model, MyEntity entity)
{
    if (model == null)    //New code to generate
    {
        entity = null;
        return entity;
    }                    //End new code to generate
    entity.Prop1 = model.Prop1;
    entity.Prop2 = model.Prop2;
}
StillLearnin commented 5 years ago

I suppose a case could also be made to simply return without setting anything.

cezarypiatek commented 5 years ago

Hi

The problem of the null values is much broader but it's worth to discuss it:

StillLearnin commented 5 years ago

Been mulling over your reply and the excellent questions it contains. It does seem that the problem of null is much broader than what I first thought.

I generally handle reference type sub-properties using another mapper injected for them. This means that in my experience the null problem will be handled by a sub-mapper. So leaving sub-properties aside for the moment, I think the question becomes:

What should be done when the source is null?

Options:

cezarypiatek commented 5 years ago

Hi Sorry for the late reply. I was thinking about this problem and I decided to not implement anything related to this null handling. The main idea behind the MappingGenerator is to facilitate a simple scaffolding of mapping method based on the simple and obvious rules and allows to customize generated code. Everybody has different expectations for the null handling and this should be handled by manual adjustment of generated code depending on the given case.

StillLearnin commented 5 years ago

Makes sense to me. Thanks for considering it.