Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework - How to load empty children
    primarykey
    data
    text
    <p>Am getting started using Entity Framework and have run into a problem.</p> <p>Say I have 2 tables in my database. One called Agent that contains an ID and a password and another table called AgentDetail that contains more information about the Agent. However, there might not be a corresponding AgentDetail record for every Agent record.</p> <p>I have these 2 classes to represent those 2 tables:</p> <pre><code>public class Agent { public string AgentId { get; set; } public string Password { get; set; } public virtual AgentDetail AgentDetail { get; set; } } public class AgentDetail { public string AgentDetailId { get; set; } public string AgentName { get; set; } public string Postcode { get; set; } } </code></pre> <p>Using EF I can add data to the database OK. I can also retrieve data OK when there is a corresponding record in both tables.</p> <pre><code> var agents = from a in context.Agents select a; return View(agents.ToList()); </code></pre> <p>However I get a NullReferenceException in my view when rendering values within AgentDetail if that record doesn't exist in the AgentDetail table.</p> <p>Now that's totally expected as there is no AgentDetail record.</p> <p>My question is how do I get EF to create an AgentDetail with empty values when the record doesn't exist in the table.</p> <p>Can I add an empty child object in the LINQ query - something like:</p> <pre><code> var agents = (from a in rb.Agents select new { AgentId = a.AgentId, Password = a.Password, AgentDetail = a.AgentDetail == null ? new AgentDetail() : a.AgentDetail, }).ToList(); </code></pre> <p>(the above doesn't work however as I get the following message:</p> <p>The entity or complex type 'Models.AgentDetail' cannot be constructed in a LINQ to Entities query.)</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.
    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