Jesse
Jesse

Reputation: 975

Entity Framework Navigation Properties not loading

I'm new to Entity Framework. I'm using the code first option. Below I have a basic model. The database was created properly and the records persist properly but when I run the test method (defined after the model) a second time my header record loads fine, but my navigation property, Details, does not reload. What am I doing wrong?

class Header
{
    public int HeaderId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Detail> Details { get; set; } = new List<Detail>();
}

class Detail
{
    public int DetailId { get; set; }
    public string Name { get; set; }
    public int HeaderId { get; set; }
    [ForeignKey("HeaderId")]
    public virtual Header Header { get; set; }
}

class MyContext : DbContext
{
    public MyContext() : base("EfTest")
    {
        this.Configuration.LazyLoadingEnabled = true;
    }

    public virtual DbSet<Header> Headers { get; set; }
}

private static void DoIt()
{
    using (var ctx = new MyContext())
    {
        var hdr = (
            from header in ctx.Headers
            where header.Name == NAME
            select header).FirstOrDefault();
        if (hdr == null)
        {
            hdr = new Header();
            hdr.Name = NAME;
            ctx.Headers.Add(hdr);
            MessageBox.Show("Header not found; created.");
        }
        else
        {
            MessageBox.Show("Header found!");
        }

        var det = hdr.Details.FirstOrDefault();
        if (det == null)
        {
            det = new Detail() { Name = "Hi" };
            hdr.Details.Add(det);
            MessageBox.Show("Detail not found; created.");
        }
        else
        {
            MessageBox.Show("Detail found!");
        }

        ctx.SaveChanges();
    }
}

Upvotes: 0

Views: 1282

Answers (1)

user7450900
user7450900

Reputation:

Here Entity Framework use Lazy-Loading. In order to get details you should use Eager-Loading.You should use Include method in System.Data.Entity namespace to accomplish Eager-Loading.Change your query like the following.

       var hdr = (
                from header in ctx.Headers
                where header.Name == NAME
                select header).Include(h=>h.Details).FirstOrDefault();

Upvotes: 1

Related Questions