Ben Rubin
Ben Rubin

Reputation: 7331

Entity Framework Navigation Properties Are Null

I am having a problem where my Entity Framework navigation properties are null. My two models are Order and OrderLine:

class Order
{
    public string CustomerId { get; set; }
    public string OrderNumber { get; set; }

    public ICollection<OrderLine> Lines { get; set; }
}

class OrderLine
{
    public int LineNumber { get; set; }
    public string OrderNumber { get; set; }
    public string ProductId { get; set; }
    public int Quantity { get; set; }

    public Order Order { get; set; }
}

My Context class looks like this

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }
    public DbSet<OrderLine> OrderLines { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>()
            .HasKey(p => p.OrderNumber);

        modelBuilder.Entity<OrderLine>()
            .HasKey(p => new { p.OrderNumber, p.LineNumber });

        modelBuilder.Entity<OrderLine>()
            .HasRequired(p => p.Order)
            .WithMany(p => p.Lines)
            .HasForeignKey(p => p.OrderNumber);

    }
}

When I run the following code, my orders load (the message box shows the correct count), but the Order.Lines collection is null.

List<Order> orders = (from o in context.Orders select o).ToList();

// This message box shows the correct number of orders
MessageBox.Show(orders.Count.ToString());

// This line crashes because orders[0].Lines is null.  There are lines in the database that should be joining to orders[0]
MessageBox.Show(orders[0].Lines.Count.ToString());

I've looked at a lot of examples, and I can't figure out what I'm doing incorrectly.

Upvotes: 2

Views: 182

Answers (1)

ocuenca
ocuenca

Reputation: 39326

You need to declare the navigation properties as virtual in order to be lazy loaded:

public class Order
{
    //...
    public virtual ICollection<OrderLine> Lines { get; set; }
}

public class OrderLine
{
    //...
    public virtual Order Order { get; set; }
}

For more info check this link to see all the requirements you need to follow.

Upvotes: 2

Related Questions