【问题标题】:AutoMapper - Map source object as property in the destination objectAutoMapper - 将源对象映射为目标对象中的属性
【发布时间】:2021-02-22 10:27:08
【问题描述】:

我有这两门课 `

//source 
public class User
{
    [Key]
    public int UserId { get; set; }
    public string Name { get; set; }
    public int Phonee{ get; set; }
    public string Email { get; set; }
    
    public UserEducation userEducation { get; set; }
}

// destination 
public class UserEducation
{
    [Key]
    public int UserEducationId { get; set; }
    public string University { get; set; }
    public int  YearOfGraduation { get; set; }

    public int UserId { get; set; }
    public User User { get; set; }
}

我要做的是尝试将源对象映射到目标对象作为其属性之一

userEducation = _mapper.Map<UserEducation>(User);
CreateMap<User.UserEduation>().FromMember(dir => dir.User, ???);

【问题讨论】:

  • @Hubssein Shukri,你能点击“接受这个答案”吗?

标签: entity-framework-core asp.net-identity automapper


【解决方案1】:

你可以参考这个例子。它可以很好地将User映射到UserEducation

public class CustomMapper : Profile
{
    public CustomMapper()
    {
        CreateMap<User, UserEducation>()
            .ForMember(dir => dir.User, x=>x.MapFrom(t=> new User
            {
                UserId=t.UserId,
                Name=t.Name,
                Email=t.Email,
                Phonee=t.Phonee 
            }));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2017-06-19
    • 2017-09-26
    • 2017-04-07
    相关资源
    最近更新 更多