1

下面的映射有效,但我想知道是否可以用更少的配置来完成。我试过玩ForAllMembersForSourceMember但到目前为止我还没有找到任何有用的东西。

课程

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; }

    ...
}

配置

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));

询问

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

编辑这适用于相反的情况。

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);

不幸的是,Reverse()这不是一个简单的解决方案,映射不起作用。

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);
4

1 回答 1

1

我只能看到一个选项来减少配置。您可以通过将的属性重命名UserForAuthorisation为:

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

在这种情况下,嵌套User对象的属性将在没有任何额外配置的情况下被映射:

Mapper.CreateMap<Session, UserForAuthorisation>();
于 2013-02-14T15:10:56.413 回答