Last active
April 29, 2019 14:24
-
-
Save tboby/72c77dee76ce5deda6de1c883f6a23d3 to your computer and use it in GitHub Desktop.
Automapper execution plan unchanged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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