user247702
user247702

Reputation: 24232

Mapping a single child

The mapping below works, but I was wondering if it can be done with less configuration. I've tried playing around with ForAllMembers and ForSourceMember but I haven't found anything that works so far.

Classes

public class User
{
    [Key]
    public int ID { get; set; }

    public string LoginName { get; set; }

    public int Group { get; set; }

    ...
}

public class UserForAuthorisation
{
    public string LoginName { get; set; }

    public int Group { get; set; }
}

public class Session
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ID { get; set; }

    public virtual User User { get; set; }

    ...
}

Configuration

Mapper.CreateMap<Session, UserForAuthorisation>()
    .ForMember(u => u.LoginName, m => m.MapFrom(s => s.User.LoginName))
    .ForMember(u => u.Group, m => m.MapFrom(s => s.User.Group));

Query

UserForAuthorisation user = this.DbContext.Sessions
    .Where(item =>
        item.ID == SessionID
        )
    .Project().To<UserForAuthorisation>()
    .Single();

Edit This works for the reverse.

Mapper.CreateMap<UserForAuthorisation, User>();

Mapper.CreateMap<UserForAuthorisation, Session>()
    .ForMember(s => s.User, m => m.MapFrom(u => u));

var source = new UserForAuthorisation()
{
    Group = 5,
    LoginName = "foo"
};
var destination = Mapper.Map<Session>(source);

Unfortunately, Reverse() isn't the easy solution, mapping doesn't work.

Mapper.CreateMap<UserForAuthorisation, User>().ReverseMap();

Mapper.CreateMap<UserForAuthorisation, Session>()
    .ForMember(s => s.User, m => m.MapFrom(u => u)).ReverseMap();

var source = new Session()
{
    User = new User()
    {
        Group = 5,
        LoginName = "foo"
    }
};
var destination = Mapper.Map<UserForAuthorisation>(source);

Upvotes: 1

Views: 78

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

I can see only one option to do less configurations. You can use benefit of flattering by renaming properties of UserForAuthorisation class to:

public class UserForAuthorisation
{
    public string UserLoginName { get; set; }
    public int UserGroup { get; set; }
}

In this case properties of nested User object will be mapped without any additional configuration:

Mapper.CreateMap<Session, UserForAuthorisation>();

Upvotes: 1

Related Questions