Search code examples
c#asp.netentity-frameworkinner-joinef-core-2.0

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; }
}

How do I bind my data from the inner join to the ViewModel class, so I can display it on a view?

I've tried ap = appointmentsViewModel; but it gives me an error. How do I do that?


Solution

  • You need to select AppointmentsViewModel instead of anonymous type as following:

    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);
    }