skip to Main Content

I’m building a web app using Entity Framework Core.

I have a view model with a property:

Public IEnumerable<AppointmentDTO> Appointments 

Appointment has a foreign key DoctorId.

Now in the view where Im using the view model, I have:

@foreach (var doc in Model.Doctors)
{
    var appointment = Model.Appointments?.FirstOrDefault(a => a.DoctorId == doc.Id);
}

The issue is all DoctorId are returned as null, for all appointments, even though it’s not.

Does anybody know what the issue could be?

Appointment model

public int? DoctorId { get; set; }
public Doctor Doctor { get; set; }

Doctor model

public List<Appointment>? Appointments { get; set; }

I thought it could be because doctorId is nullable, so I made it required, but that didn’t work, either.

2

Answers


  1. public class AppointmentDTO {
    public int? DocId { get; set; }

      public Doctor Doctor { get; set; }
    

    viewModel:

    public class CalendarViewModel
    {
    public IEnumerable? Doctors { get; set; }

        public IEnumerable<AppointmentDTO>? Appointments { get; set; }
    

    view:

    @model ClinicaApp.ViewModels.CalendarViewModel

    @{
    var selectedSections = ViewData["SelectedSections"] as List; }

    <div class="paging">
        <a href="#" class="previous" onclick="updateDate(-1)" id="arrow">&laquo; Previous</a>
        <input class="date" type="text" value="" id="flexCheckDefault">
    
        <a href="#" class="next" onclick="updateDate(1)" id="arrow">Next &raquo;</a>
    </div>
    
    
    @if (Model.Doctors != null)
    {
        @foreach (var doc in Model.Doctors)
        {
            // var appointment = Model.Appointments?.FirstOrDefault( a => a.DoctorId ==1 );
            var appointment = Model.Appointments?.FirstOrDefault(a => a.DoctorId == 1);
            if (appointment != null)
                Console.WriteLine("true");
        }
    }
    
    Login or Signup to reply.
  2. Make sure in the controller you have define the view model , set the list Doctors and Appointments value.

    like:

     public IActionResult Index()
     {
         var doctors= _context.Doctors.ToList();
         var appointments= _context.Appointments.ToList();//you can set the data as your way
         var model = new yourViewModel();
         model.Doctors = doctors;
         model.Appointments = appointments;   
         return View(model);
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search