我有一个场景,我必须做以下映射
public class Company : BaseEntity
{
public string Name { get; set; }
public virtual ICollection<CompanyService> CompanyServices { get; set; }
}
public class Service : BaseEntity
{
public string Name { get; set; }
public virtual ICollection<CompanyService> CompanyServices { get; set; }
}
public class CompanyService : BaseEntity
{
public long CompanyID { get; set; }
public virtual Company Company { get; set; }
public long ServiceID { get; set; }
public virtual Service Service { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和相应的View Models
public class CompanyViewModel : BaseEntity
{
public string Name { get; set; }
public string Services { get; set; }
}
public class ServiceViewModel : BaseEntity
{
public string Name { get; set; }
}
public class CompanyServiceViewModel : BaseEntity
{
public string ServiceName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想使用AutoMapper进行映射,其中我应该在CompanyViewModel类中将Service的名称作为逗号分隔的字符串
Mapper.CreateMap<Company, CompanyViewModel>();
Run Code Online (Sandbox Code Playgroud)
Ger*_*old 12
您可以使用以下映射:
Mapper.CreateMap<Company, CompanyViewModel>()
.ForMember(dest => dest.Services,
m => m.MapFrom(src => string.Join(", ", src.CompanyServices
.Select (s => s.Service.Name))));
Run Code Online (Sandbox Code Playgroud)
但请注意,您将无法IQueryable
直接在LINQ to Entities中使用映射,因为EF将抛出异常,无法将该string.Join
部分转换为SQL.你必须使用AsEnumerable
然后进行映射,例如:
Mapper.Map<T>(context.Entities.AsEnumerable(). ...)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3805 次 |
最近记录: |