Issue Creating Mapping for join entity from DTOs

14 views
Skip to first unread message

Felix James

unread,
Jun 13, 2017, 2:38:52 AM6/13/17
to AutoMapper-users
Hi,
I have the following code snippet. 
I wish to save my User entity after mapping along with related entities as a single transaction. i.e. Entity framework will update the UserBranchSpecialism Table with the generated UserId as expected.
I can't find a way of specifying the User property of the UserBranchSpecialism as part of my mapping configuration i.e. I would like to specify 

// ENTITIES
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public BranchProfile BranchProfile { get;set; }
}

public class BranchProfile
{
public int Id { get; set; }
public string Name { get; set; }
public List<UserBranchSpecialism> Specialisms { get; set; }
}

public class BranchSpecialism
{
public int Id { get; set; }
public string Name { get; set; }
}

public class UserBranchSpecialism
{
public User User { get; set; }
public BranchSpecialism BranchSpecialism { get;set; }
public int BranchSpecialismId { get;set; }
public int UserId { get; set; }
}

// DTOS
public class UserCreateDto
{
public string Name { get;set; }
}
public class BranchProfileDto
{
public string Name { get;set; }
public List<int> BranchSpecialismIds { get;set; }
}

// MAPPING CONFIG
CreateMap<UserCreateDto, User>();
CreateMap<BranchProfileDto, BranchProfile>()
.ForMember(dest => dest.Specialisms,
opt => opt.MapFrom(src => src.BranchSpecialismIds
.Select(id => new UserBranchSpecialism() { BranchSpecialismId = id }).ToList()));




Ideally,
I will like to do something like this:

// MAPPING CONFIG
CreateMap<UserCreateDto, User>();
CreateMap<BranchProfileDto, BranchProfile>()
.ForMember(dest => dest.Specialisms,
opt => opt.MapFrom(src => src.BranchSpecialismIds
.Select(id => new UserBranchSpecialism() { BranchSpecialismId = id, User = ???? }).ToList()));

How can i achieve with the mappings split out as above or using any other alternative means?
Thanks in advance.
Reply all
Reply to author
Forward
0 new messages