我正在使用代码优先迁移来创建实体。我的实体看起来像这样:
public class User
{
private string userWholeName = string.Empty;
private ICollection<UsersInRoles> usersInRoles;
public User()
{
this.UserId = Guid.NewGuid();
this.usersInRoles = new System.Collections.Generic.HashSet<UsersInRoles>();
}
[Key]
public Guid UserId { get; set; }
//TODO: check for resource names and for all models
[Required(AllowEmptyStrings = false, ErrorMessage = null)]
public string UserName { get; set; }
[Required(AllowEmptyStrings = false)]
[MaxLength(30)]
public string Password { get; set; }
public virtual ICollection<UsersInRoles> UsersInRoles
{
get { return this.usersInRoles; }
set { this.usersInRoles = value; }
}
}
我的UsersInRolesClass:
public class UsersInRoles
{
public UsersInRoles()
{
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UsersInRolesId { get; set; }
public Guid UserId { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
public virtual User User { get; set; }
}
我的角色课程:
public class Role : Interfaces.IRole
{
private ICollection<UsersInRoles> usersInRoles;
public Role()
{
this.usersInRoles = new HashSet<UsersInRoles>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
[Required]
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public virtual ICollection<UsersInRoles> UsersInRoles
{
get
{
return this.usersInRoles;
}
set
{
this.usersInRoles = value;
}
}
}
所以这些是我的数据库实体。我试图将它们映射到:
public class UserDTO
{
//other properties same as in User entity
IList<RoleDTO> Roles { get; set; }
}
public class RoleDTO
{
int RoleId { get; set; }
string RoleName { get; set; }
}
每个属性都已映射,但角色不是。我正在尝试这个:
Mapper.Initialize(cfg => cfg.CreateMap<UserDTO, User>().ForMember(dest => dest.UsersInRoles, opt => opt.ResolveUsing(c=>c.Roles.Select(f=>new UsersInRoles() { Role = new Role() { RoleId = f.RoleId,RoleName = f.RoleName}, RoleId = f.RoleId,UserId = c.UserId }))));
任何想法?