Denis V
Denis V

Reputation: 421

Include query result to List

I have a list of Hospitals

Hospital model:

public class Hospital
{
    [Key]
    public int HospitalID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<HospitalSpeciality> HospitalSpecialities { get; set; }
    public virtual ICollection<UserHospital> UserHospitals { get; set; }
}

and I have users associated to hospital. Model:

public class UserHospital
{
    [Key]
    public int UserHospitalID { get; set; }

    public int HospitalID { get; set; }
    public Hospital Hospitals { get; set; }

    public string Id { get; set; }
    public ApplicationUser Users { get; set; }
}

I need, on my list, return also the number of the user's that are associated to the Hospital.

This query is easy if I have only 1 hospital, but in my scenario, I have a list of hospitals

Controller:

    public ActionResult Index()
    {
        var result = db.Hospitals.ToList();
        return View(result);
    }

I really don't know how to include the result of the query (number of users) on my list.

My view:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.HospitalID }) |
            @Html.ActionLink("Details", "Details", new { id=item.HospitalID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.HospitalID })
        </td>
    </tr>
}

Upvotes: 0

Views: 1602

Answers (1)

Heberda
Heberda

Reputation: 820

It looks like you need to ensure the users are being returned in the query... Like so:

public ActionResult Index()
{
    var result = db.Hospitals
                   .Include("UserHospitals")
                   .Include("UserHospitals.Users")
                   .ToList();
    return View(result);
}

Even if they are virtual, lazy loading won't occur because you are accessing the property in your razor view. The Include is forcing Eager Loading.

Alternatively, expose another Dbset...

public DbSet<User> Users { get; set; }

Now you can select the following:

db.Users.Where(x => !x.active).ToList();

Let me know how you get on :)

Upvotes: 1

Related Questions