Note that there are some explanatory texts on larger screens.

plurals
  1. POLazy-Loading with two navigation properties
    primarykey
    data
    text
    <h2>The Setup</h2> <p>I have a fairly simple 3 class set up as follows. There are a bunch of other properties of course, but they are not relevant here.</p> <p><strong>Models</strong></p> <pre><code>public class Employee { public int EmployeeId { get; set; } public string UserName { get; set; } public string Name { get; set; } public ICollection&lt;Position&gt; Positions { get; set; } } public class Position { public int PositionId { get; set; } public int EmployeeId { get; set; } [ForeignKey("EmployeeId")] public Employee Employee { get; set; } public int location { get; set; } [ForeignKey("location")] public Location Location { get; set; } } public class Location { public int LocationId { get; set; } public string Name { get; set; } } </code></pre> <p><strong>Controller</strong></p> <pre><code>public ActionResult Index() { string username = User.Identity.Name; Employee emp = context.Employees.Include(e =&gt; e.Positions).FirstOrDefault(e =&gt; e.UserName == username); return View(emp); </code></pre> <p><strong>View</strong></p> <pre><code>@model Employee &lt;h1&gt;Hi @Model.Name&lt;/h1&gt; &lt;ul&gt; @foreach (var position in @Model.Positions) { &lt;li&gt;@position.Name - @position.Location.Name&lt;/li&gt; } &lt;/ul&gt; </code></pre> <h2>The Problem</h2> <p>Now the problem is that because of Lazy Loading. I get a <em>NullReferenceException</em> on the <code>@item.Location.Name</code> call. It is loading the Position just fine (the item in the foreach).</p> <p>I have tried changing my Include to be:</p> <pre><code>context.Employees.Include("Positions.Location").FirstOrDefault(e =&gt; e.UserName == username); </code></pre> <p>But then I get the error: <em>More than one item in the metadata collection match the identity 'Location'.</em></p> <p>If I change the <code>Location</code> property on <code>Position</code> to <code>PositionLocation</code> then I get: <em>System.Reflection.AmbiguousMatchException: Ambiguous match found.</em></p> <p>Should I be using a ViewModel that I load with multiple queries to my context in my controller? That seems like a lot more code to maintain and I'd rather not if I don't have to.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload