1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.