我正在尝试将两个实体映射到它的ViewModel,但它是错误的,因为Visual Studio显示了StackOveflowException。
使用EF6的实体:
public partial class Users
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Users()
{
this.Mayorista = new HashSet<Mayorista>();
}
public int UserId { get; set; }
public string Name { get; set; }
public System.DateTime BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public bool Active { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Mayorista> Mayorista { get; set; }
}
public partial class Mayorista
{
public int idMayorista { get; set; }
public int idUser { get; set; }
public string nombre { get; set; }
public virtual Users Users { get; set; }
}
的ViewModels:
public class UsersViewModel
{
public int UserId { get; set; }
public string Name { get; set; }
public System.DateTime BirthDate { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public bool Active { get; set; }
public virtual ICollection<MayoristaViewModel> Mayorista { get; set; }
}
public class MayoristaViewModel
{
public int idMayorista { get; set; }
public int idUser { get; set; }
public string nombre { get; set; }
public virtual UsersViewModel Users { get; set; }
}
使用Automapper实现:
var user = _service.GetById(id);
Mapper.Initialize(cfg => {
cfg.CreateMap<Users, UsersViewModel>();
cfg.CreateMap<Mayorista, MayoristaViewModel>();
});
var userView = Mapper.Map<Users, UsersViewModel>(user);
Mapper初始化是正确的,但是当我执行Mapper.Map时,Visual Studio会显示StackOverFlowException。
谢谢!。