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

Enhancement to generate mapping that creates new or updates existing #45

Closed aeslinger0 closed 5 years ago

aeslinger0 commented 5 years ago

I think it'd be useful to allow an additional parameter that is the same as the destination type which could be used to update an existing object if it exists. So, given a signature like this:

public MyEntity Map(MyModel model, MyEntity entity)
{
}

It could generate code like this:

public MyEntity Map(MyModel model, MyEntity entity)
{
    entity = entity ?? new MyEntity();
    entity.Prop1 = model.Prop1;
    entity.Prop2 = model.Prop2;
    return entity;
}

It should work the same if using an optional parameter: public MyEntity Map(MyModel model, MyEntity entity = null)

What do you think?

cezarypiatek commented 5 years ago

Hi @aeslinger0 Sorry for the delay, I focused on another issue reported by you #44 and totally forgot about this one. I would like to get back to this subject if it is still a matter.

Could you provide a sample situation when this type of proposed mapping would be useful?

aeslinger0 commented 5 years ago

I think I want to take back this request. I was thinking it would be handy for the mapping function to instantiate a new object if an existing object doesn't exist. Like when you have a "Save" method that would upsert an entity. I now think it's actually better to create the new instance outside of the mapping function versus what I wrote above since you could accidentally create a new instance when you meant to update an existing instance if the existing instance could not be found (which should return an error instead). I see you already have a method for updating an existing object, so I don't think anything else needs to be done. So, nevermind :)