Skip to content

Instantly share code, notes, and snippets.

@tboby
Last active April 29, 2019 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tboby/72c77dee76ce5deda6de1c883f6a23d3 to your computer and use it in GitHub Desktop.
Save tboby/72c77dee76ce5deda6de1c883f6a23d3 to your computer and use it in GitHub Desktop.
Automapper execution plan unchanged
static void Main(string[] args)
{
var caseView = new CaseView(){
User = new UserView{
UserID = 5
},
UserID = 5
};
Mapper.Initialize(cfg =>
{
cfg.AddProfile(typeof(CaseProfileDefaultMap));
});
var configuration = new MapperConfiguration(cfg => cfg.CreateMap<CaseView, Case>());
var executionPlan = configuration.BuildExecutionPlan(typeof(CaseView), typeof(Case));
var result1 = Mapper.Map<CaseView, Case>(caseView);
Mapper.Reset();
Mapper.Initialize(cfg =>
{
cfg.AddProfile(typeof(CaseProfileWithNull));
});
var configuration2 = new MapperConfiguration(cfg => cfg.CreateMap<CaseView, Case>());
var executionPlan2 = configuration.BuildExecutionPlan(typeof(CaseView), typeof(Case));
var result2 = Mapper.Map<CaseView, Case>(caseView);
// Compare execution plans
// Either the plans are the same, and the values are the same:
executionPlan.ShouldBe(executionPlan2);
((int?)(result2?.User?.UserID)).ShouldBe((int?)(result1?.User.UserID));
// Or the plans are different
executionPlan.ShouldNotBe(executionPlan2);
}
public class UserView {
public int UserID {get; set;}
}
public class User {
public int UserID { get; set; }
}
public class UserChild : User {
}
public class Case
{
public virtual User User {get; set;}
public int? UserID {get; set;}
}
public class CaseView
{
public UserView User {get; set;}
public int? UserID {get; set;}
}
public class CaseProfileDefaultMap : Profile {
public CaseProfileDefaultMap()
{
CreateMap<CaseView, Case>();
CreateMap<UserView, User>();
}
}
public class CaseProfileWithNull : Profile
{
public CaseProfileWithNull()
{
CreateMap<CaseView, Case>()
.ForMember(x => x.User, opts => opts.MapFrom(src => (User)null));
CreateMap<UserView, User>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment