我正在使用Visual Studio 2019和.net core 3.1。我有一个ViewModel可以在视图上显示区域及其国家,国家名称,而不是ID和外键。一个国家有几个地区。
我尝试使用linq和EF查询,但无法获取映射。
public IActionResult Index()
{
var data = (from r in _context.CustomerRegions
join c in _context.CustomerCountries
on r.IdCustomerCountry equals c.IdCustomerCountry
select new
{
r.IdCustomerRegion,
r.CustomerRegion,
c.IdCustomerCountry,
c.CustomerCountryName
}).OrderBy(m => m.CustomerCountryName);
var data2 = _context.CustomerRegions
.Include("CustomerContry.CustomerCountryName").FirstOrDefault();
List<CustomerCountryRegionVM> regionsWithCountries = _mapper
.Map<List<CustomerRegions>, List<CustomerCountryRegionVM>>(data2);
...
}
数据2。您无法从CustomerRegions转换为通用列表CustomerCountryRegionVM
数据。您无法从“可查询的订单”转换为通用列表
关于映射类:
CreateMap<CustomerCountryRegionVM, CustomerRegions>();
CreateMap<CustomerRegions, CustomerCountryRegionVM>()
.ForMember(dest => dest.CustomerCountryName, opt =>
opt.MapFrom(src => src.CustomerCountry));
视图模型:
public class CustomerCountryRegionVM
{
public int IdCustomerRegion { get; set; }
public string CustomerRegion { get; set; }
public int IdCustomerCountry { get; set; }
public string CustomerCountryName { get; set; }
}
模型:
public class CustomerRegions
{
[Key]
public int IdCustomerRegion { get; set; }
[StringLength(50, ErrorMessage = "Longitud máxima para la región: 50")]
public string CustomerRegion { get; set; }
[ForeignKey("IdCustomerCountry")]
public int IdCustomerCountry { get; set; }
public CustomerCountries CustomerCountry { get; set; }
public ICollection<CustomerCities> CustomerCities { get; set; }
}
****************************更新**************** >
var configuration = new MapperConfiguration(cfg => cfg.CreateMap<CustomerCountries, CustomerCountryRegionVM>()
.ForMember(dto => dto.CustomerRegion, conf => conf.MapFrom(ol => ol.CustomerRegions)));
//I can´t see the next field on the intellicense
public List<CustomerCountryRegionVM> GetLinesForOrder(int orderId)
{
using (var context = new orderEntities())
{
return context.OrderLines.Where(ol => ol.OrderId == orderId)
.ProjectTo<CustomerCountryRegionVM>(configuration).ToList();
}
}
答案 0 :(得分:1)
几天后,我找到了解决方法
CreateMap<CustomerRegions, CustomerCountryRegionVM>()
.ForMember(x => x.CustomerCountryName, opt => opt.MapFrom(z => z.CustomerCountry.CustomerCountryName));
在控制器上
var customerRegions = await _context.CustomerRegions
.Include(c=>c.CustomerCountry)
.ToListAsync();
List<CustomerCountryRegionVM> regions = _mapper.Map<List<CustomerRegions>,
List<CustomerCountryRegionVM>>(customerRegions);