Ian Davies
Ian Davies

Reputation: 13

Loading data from one table via another

I am trying to load each staff members holiday record but I am unable to populate holiday records.

Here is the code from my controller:

public class HomeController : Controller
{
    private HRModel.db_HRSystemModel db = new HRModel.db_HRSystemModel();

    public IActionResult Index()
    {

        var staff = (from s in db.Hrstaffpersonaldetails
                     where s.Firstname == "Ian"
                     select s).ToList();
        return View(staff);
    }
}

and here is the code from my view:

<div>
<h4>Staff</h4>
<hr />
@foreach (var s in Model)
{
    <dl class="dl-horizontal">
        <dt>
            First Name:
        </dt>
        <dd>
            @s.Firstname
        </dd>
        <dt>
            Surname:
        </dt>
        <dd>
            @s.Surname
        </dd>
        <dt>
            Username:
        </dt>
        <dd>
            @s.Username
        </dd>
        @foreach (var hr in s.Hrstaffholidayrecords)
        {

            <dt>
                date:
            </dt>
            <dd>
                @hr.Startdate
            </dd>

        }
    </dl>
}
</div>

When I currently run what I have (on .NET Core 1.1), holiday records returns 0 records from the database. I'm not really sure if I'm missing something or I'm doing it wrong.

Thanks, Ian

Upvotes: 1

Views: 36

Answers (2)

胡玮文
胡玮文

Reputation: 98

Change the controller code to this should work.

public class HomeController : Controller
{
    private HRModel.db_HRSystemModel db = new HRModel.db_HRSystemModel();

    public IActionResult Index()
    {
        var staff = db.Hrstaffpersonaldetails
                    .Include(s => s.Hrstaffholidayrecords)
                    .Where(s => s.Firstname == "Ian")
                    .ToList();
        return View(staff);
    }
}

This is called eager loading. Read more at https://learn.microsoft.com/en-us/ef/core/querying/related-data

Besides, the db context object is supposed to be injected into controller using DI. Read more at https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection

Upvotes: 1

hopeless
hopeless

Reputation: 96

looks like lazy loading, but not sure, not that strong at this) you should read smth about fluent API

Upvotes: 1

Related Questions