如何在使用AutoMapper时忽略内部嵌套对象

时间:2015-08-07 16:55:00

标签: c# automapper

您好我有课程:

班级用户

public class User
{
    public Int64 Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }        
    public Profile Profile { get; set; } //EF one to one
}

课程资料

    public class Profile 
{
    public Int64 Id { get; set; }
    public string Skype { get; set; }
    public string Phone { get; set; }
    public string Mobile { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual User User { get; set; } //This is because EF Mappings
}

班级用户DTO

public class UserDTO
{
    public string Name { get; set; }
    public string Email { get; set; }        
    public Profile Profile { get; set; }
}

我完成了将用户映射到UserDTO的配置

Mapper.CreateMap<User, UserDTO>();

由于实体框架一对一关系,我需要 Profile.User ,但我不希望Profile.User显示在映射。

如何忽略Profile.User?

1 个答案:

答案 0 :(得分:3)

您可以使用省略UserProfileDTO

User课程
public class UserProfileDTO
{
    public string Skype { get; set; }
    public string Phone { get; set; }
    public string Mobile { get; set; }
    public ICollection<AddressDTO> Addresses { get; set; }
}

public class UserDTO
{
    public string Name { get; set; }
    public string Email { get; set; }
    public UserProfileDTO Profile { get; set; }
}

Mapper.CreateMap<User, UserDTO>();
Mapper.CreateMap<Profile, UserProfileDTO>();