Asp.net Core EF Core Inner Join,以及数据到View Model

Asp.net Core EF Core Inner Join, and data to View Model

public async Task<IActionResult> Index()
{
    AppointmentsViewModel appointmentsViewModel = new AppointmentsViewModel();

      var ap = 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();



    return View(ap);
}
public class AppointmentsViewModel
{
    public int No { get; set; }

    public DateTime Date { get; set; }

    public string Name { get; set; }
    public string Ref { get; set; }
}

如何将我的数据从内部联接绑定到 ViewModel class,以便我可以在视图上显示它?

我试过 ap = appointmentsViewModel; 但它给了我一个错误。我该怎么做?

您需要 select AppointmentsViewModel 而不是 anonymous type,如下所示:

public async Task<IActionResult> Index()
{
      var ap = 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();


    return View(ap);
}