Repository navigation
Description
I'm writing a restful api and in my use case I am trying to map a nullable type on my source to a non-nullable property on my destination. I want it to ignore mapping properties if the source value is null. I want this because it is a really elegant solution for me to deserialize a partial json request into my object and only update fields on my entity object that were actually passed to my dto. See my code below (note, I've removed all my Entity Framework junk).
These are my source (ScriptDto) and destination (Script) classes.
public class ScriptDto
{
public Guid Id { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ScriptLanguage? Language { get; set; }
public string Target { get; set; }
public string ScriptBody { get; set; }
public DateTime? LastExecuted { get; set; }
public Guid? LastExecutedBy { get; set; }
}
public class Script : IEntity
{
public Guid Id { get; private set; }
public string Name { get; set; }
public ScriptLanguage Language { get; set; }
public string Target { get; set; }
public string ScriptBody { get; set; }
public DateTime LastExecuted { get; set; }
}This is my web api routed method
[HttpPut("{id}")]
public IActionResult UpdateScript(string id, [FromBody]ScriptDto scriptDto, [FromServices]IDatabaseConfigurationLoader loader)
{
Script script = //code to get my script object from the database
if (script == null) { return NotFound(); }
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<ScriptDto, Script>()
.ForMember(y => y.Id, opt => opt.Ignore())
.ForAllOtherMembers(opt =>
{
opt.Condition((src, dest, srcValue) =>
{
return srcValue != null; //ignore properties on dto that are null
});
});
});
_mapper = config.CreateMapper();
//map dto to entity
_mapper.Map(dto, script);
//save changes to database
return new ObjectResult(MapToDto(script)); //return updated object
}What I would expect to happen with this, is if the source property is null the condition function evaluates to false and the property mapping is skipped. That is not what is happening for the nullable properties on my source object. After setting a break point inside the conditional function I realized that my source property values were being cast to the destination type (I assume) before they are passed to the conditional function. So where I would expect "srcValue" to be null it was actually already cast to its non-nullable default. If for example, I sent the following json PUT request to my service at api/v1/scripts/somescriptid
{ "scriptBody": "test body" }then it would deserialize into a DTO object with mostly null properties, with the exception of the ScriptBody property. But when it gets mapped to my destination object, the DateTime? LastExecuted property which is null (for example) has its value cast to a non-nullable DateTime prior to being passed to the conditional function. Which of course causes my conditional function to evaluate to true and thus the destination property is overwritten.
I imagine I am having this issue because I am trying to map a nullable property on my source to a non-nullable property on my destination. When I change the property on my destination object to a nullable type then it works the way I would expect. That said, I do not want nullable types where they aren't required on my entity object. I'm using the latest dev build on myget, 5.2.0-alpha-01223.
Activity
lbargaoanu commentedon Sep 28, 2016
I don't think this is going to happen. It might break a lot of people.
CicerosPatience commentedon Sep 28, 2016
I get that it is probably a breaking change, but I also think its the correct way to do this. The only value I see to casting the source property before its passed into the conditional function is that it validates that the properties to be mapped are of the same type. If that's necessary, it can certainly be handled in a better way, either as a separate option or by the developer handling it inside the conditional function.
Alternatively, I would suggest adding a separate function to options that allows this to be done. As it is, there is no other way that I am aware of to accomplish this use case with automapper.
lbargaoanu commentedon Sep 28, 2016
You can check against the default value for the value type, but that's not exposed right now through the interface, so you need a cast.
Update : no need for a cast anymore.
lbargaoanu commentedon Sep 28, 2016
@jbogard Maybe include this in AM? People seemed to want similar things before.
jbogard commentedon Oct 5, 2016
What's not exposed? Just the member?
lbargaoanu commentedon Oct 5, 2016
Yes, the destination member type. But the final code doesn't look that bad :)
alex-yakovenko commentedon Nov 6, 2016
This bug appears when you use retrieved via NuGet instance of AutoMapper.dll. In this case added by Condition method expression obtains wrong value in sourceValue parameter. The bug disappeared after I rebuilt AutoMapper on local machine.
Here is test code which I use to reproduce the bug:
lbargaoanu commentedon Nov 6, 2016
Most likely #1634. You can use the MyGet build instead.
lbargaoanu commentedon Dec 7, 2016
The solution is above. CreateMissingTypeMaps is gonna get you into trouble eventually.
lbargaoanu commentedon Dec 7, 2016
Then I guess you should try something else.
lbargaoanu commentedon Dec 7, 2016
Or a PR. @jbogard seems OK with it.
32 remaining items
lbargaoanu commentedon Feb 11, 2017
You need a condition for that. The comment was only for that particular case. Cargo cult programming won't get you anywhere.
krishnandusarkar commentedon Feb 11, 2017
@lbargaoanu Well, this is what I was asking. What kind of condition should I put in there? Do I need another resolver for string? Or I can plug the code in same Resolver. Sorry, but I do not get the approach.
levitatejay commentedon May 9, 2017
Here is a solution that works with
ForAllMembersif all the properties have the same names between objectsand use it like so:
GFoley83 commentedon Oct 3, 2017
@levitatejay How would I update your
Resolvemethod to allow for the scenario when there's no destination / source member to map to? E.g. if my source object doesn't have a property that the destination has.petrosmm commentedon May 11, 2018
in #1703 (comment) @lbargaoanu used
Nullable.GetUnderlyingType(pm.SourceType)why would he/she have needed to use that method instead of just usingpm.SourceType; I am not sure I understand the intent by it? Also if I usedpm.SourceType.UnderlyingSystemTypeinstead what issue could I run into?lbargaoanu commentedon May 12, 2018
Because this happens only in this particular case, for the rest, the source member is null as expected.
Yon2068 commentedon Aug 2, 2018
This is an extension
Works for all Nullable types
How to use it?
AutoMapper.Mapper.Initialize(cfg => { cfg.IgnoreSourceWhenNull(); });Here's the extension
AutoMapperExtensions.cs.zip
lbargaoanu commentedon Aug 3, 2018
You don't need more than one instance of that resolver. You can create it in your extension and pass that instance.
Yon2068 commentedon Aug 3, 2018
@lbargaoanu
With this extension:
ObjectId can't convert to string
How do I do that?
lbargaoanu commentedon Aug 3, 2018
I have no idea what you're saying.
Yon2068 commentedon Aug 3, 2018
@lbargaoanu
System.InvalidCastException : Unable to cast object of type 'MongoDB.Bson.ObjectId' to type 'System.String'.lbargaoanu commentedon Aug 3, 2018
That's most likely an issue with your own code.
Yon2068 commentedon Aug 3, 2018
I using
ForAllPropertyMapsto ignore allNullable<>ForAllPropertyMaps()
Resolve()
lock commentedon May 6, 2019
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.