实体框架导航属性为空

时间:2015-08-15 01:14:38

标签: entity-framework

我遇到的问题是我的Entity Framework导航属性为null。我的两个模型是Order和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; }
}

我的Context类看起来像这样

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);

    }
}

当我运行以下代码时,我的订单加载(消息框显示正确的计数),但Order.Lines集合为空。

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());

我看了很多例子,我无法弄清楚我做错了什么。

1 个答案:

答案 0 :(得分:2)

您需要将导航属性声明为virtual才能延迟加载:

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

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

有关详细信息,请查看此link以查看您需要遵循的所有要求。