ASP.NET Core EF Core内连接数据如何绑定到ViewModel并在视图显示?
如何将EF Core内连接查询结果绑定到AppointmentsViewModel?
我来帮你解决这个问题——你现在遇到的核心问题是查询返回的匿名类型集合和AppointmentsViewModel类型不匹配,直接赋值自然会报错。下面给你两种可行的实现方式,推荐第一种更高效的方案:
方案一:查询时直接投影到AppointmentsViewModel(推荐)
这种方式最省性能,因为EF Core会把投影逻辑推送到数据库端,只查询你需要的字段,然后直接构造ViewModel对象,不需要后续的类型转换。
修改你的查询代码如下:
public async Task<IActionResult> Index() { // 直接在查询中构造AppointmentsViewModel实例 var appointmentsList = await (from p in _context.Mstr_Patients join e in _context.Appointments on p.PatientID equals e.PatientID select new AppointmentsViewModel { No = e.AppointmentNo, Date = e.AppointmentDate, Name = p.FullName, Ref = e.RefDoctor }).ToListAsync(); // 直接返回ViewModel集合给视图 return View(appointmentsList); }
方案二:手动映射匿名类型到ViewModel(适合已有匿名集合的场景)
如果因为某些原因你已经得到了匿名类型的集合,也可以通过LINQ的Select方法手动将每个匿名对象转换为AppointmentsViewModel:
public async Task<IActionResult> Index() { var anonymousList = await (from p in _context.Mstr_Patients join e in _context.Appointments on p.PatientID equals e.PatientID select new { No = e.AppointmentNo, Date = e.AppointmentDate, Name = p.FullName, Ref = e.RefDoctor }).ToListAsync(); // 手动映射到ViewModel集合 var appointmentsList = anonymousList.Select(item => new AppointmentsViewModel { No = item.No, Date = item.Date, Name = item.Name, Ref = item.Ref }).ToList(); return View(appointmentsList); }
为什么你之前的ap = appointmentsViewModel;会报错?
你要注意两个关键问题:
ap是集合类型(List<匿名类型>),而appointmentsViewModel是单个AppointmentsViewModel实例,两者类型完全不兼容,赋值操作自然会抛出类型不匹配的错误。- 就算类型匹配,你也不能直接把单个实例赋值给集合变量,需要把实例放到集合里才行,但这显然不是你想要的效果——你需要的是查询结果的集合,而不是单个空ViewModel。
内容的提问来源于stack exchange,提问作者Premdas v.m
相关产品推荐
相关产品推荐

