Skip to content

Instantly share code, notes, and snippets.

@lbargaoanu
Created February 16, 2018 17:25
Show Gist options
  • Save lbargaoanu/655aa0cbe693713ba72a19070c67d3db to your computer and use it in GitHub Desktop.
Save lbargaoanu/655aa0cbe693713ba72a19070c67d3db to your computer and use it in GitHub Desktop.
static void Main(string[] args)
{
// Setup Mapper config
var config = new MapperConfiguration(c =>
{
c.DisableConstructorMapping();
c.CreateMap<RoleDTO, Role>();
c.CreateMap<UserDTO, User>()
.ForMember(entity => entity.Roles, opt => opt.Ignore());
});
// Validate Mapper config
config.AssertConfigurationIsValid();
// Test class that gets mapper by DI
var test = new Test(config.CreateMapper());
test.StartTest();
}
public class Test
{
IMapper Mapper;
public Test(IMapper mapper)
{
Mapper = mapper;
}
public void StartTest()
{
var sourceRoleDTO = new RoleDTO() { Name = "TestRole" };
var sourceUserDTO = new UserDTO
{
Name = "TestUser",
Email = "[email protected]",
Roles = new List<RoleDTO>() { sourceRoleDTO }
};
var role = Mapper.Map<Role>(sourceRoleDTO);
var user = Mapper.Map<User>(sourceUserDTO);
}
}
public class RoleDTO
{
public string Name { get; set; }
public RoleDTO() { }
}
public class UserDTO
{
public string Name { get; set; }
public string Email { get; set; }
public ICollection<RoleDTO> Roles { get; set; }
public UserDTO() { }
}
public class Role
{
public string Name { get; set; }
public Role() { }
}
public class User
{
public string Name { get; set; }
public string Email { get; set; }
public ICollection<Role> Roles { get; set; }
public User()
{
Roles = new List<Role>();
Console.WriteLine("Ok");
}
public User(string name, string email, ICollection<Role> roles) : this()
{
Console.WriteLine("Wrong");
// SHOULD NOT USE THIS CONSTRUCTOR!!!
foreach (Role r in roles)
Roles.Add(r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment