我有一个看起来像这样的EF实体:
public class Customer
{
public int IdCustomer {get; private set;}
public string Name {get; private set;}
ICollection<Specialty> Specialties {get;private set;}
}
public class Specialty
{
public int IdSpecialty {get;private set}
public int? IdSpecTypeOne {get;private set;}
public int? IdSpecTypeTwo {get;private set;}
public string Name {get;private set;}
public virtual SpecTypeOne SpecialtyTypeOne {get;private set;}
public virtual SpecTypeTwo SpecialtyTypeOne {get;private set;}
}
public class SpecTypeOne
{
public int IdSpecTypeOne {get;private set;}
public string Name {get;private set;}
}
public class SpecTypeTwo
{
public int IdSpecTypeTwo {get;private set;}
public string Name {get;private set;}
}
和ViewModel:
public class CustomerViewModel
{
public int IdCustomer
public List<CustomerSpecialtyViewModel> SpecialtyOfTypeOne {get; set;}
public List<CustomerSpecialtyViewModel> SpecialtyOfTypeTwo {get;set;}
}
public class CustomerSpecialtyViewModel
{
public int IdSpecialty {get;set;}
public int IdSpecTypeOne {get;set;}
public int IdSpecTypeTwo {get;set;}
public string SpecTypeName {get;set;}
}
基本上,我想像上面那样构建我的ViewModel,将 Specialty 和 SpecType 展平为单个ViewModel( CustomerSpecialtyViewModel )。
我将ViewModel映射为:
Mapper.CreateMap<Specialty, CustomerSpecialtyViewModel>();
Mapper.CreateMap<Customer, CustomerViewModel>()
.ForMember(d => d.SpecialtyOfTypeOne, opt => opt.MapFrom(s => s.Specialties.Where(p => p.IdSpecType == SpecTypes.TypeOne)))
.ForMember(d => d.SpecialtyOfTypeTwo, opt => opt.MapFrom(s => s.Specialties.Where(p => p.IdSpecType == SpecTypes.TypeTwo)))
如何在 CustomerSpecialtyViewModel 中包含子属性 SpecType.Name ,因为这是子属性?
CustomerSpecialtyViewModel
{
int IdSpecialty => OK
int IdSpecType => OK
string SpecTypeName => Getting 'NULL' - Need this
}
更新 我有两种类型的SpecType(一和二),但两者都有一个共同的属性(Name)。我只需要这个房产。我将在我的应用服务中检查内部的类型(一个或两个)。在View的上下文中,这无关紧要。
答案 0 :(得分:1)
我认为这应该有效:
Mapper.CreateMap<Specialty, CustomerSpecialtyViewModel>()
.ForMember(d => d.SpecTypeName, o => o.MapFrom(s => s.SpecialtyType.Name));