clearpath
clearpath

Reputation: 956

One to many navigation property is null in code first EF5

What is the proper way of defining related collections in code first Entity Framework 5? I was following this summary but something is not working.

I have the following model:

class Order
{
  public Guid Id {get; set; }
  public DateTime Created {get; set;}
  public ICollection<OrderLine> OrderLines {get; set;}
}

class OrderLine
{
  public Guid Id {get; set;}
  public Guid OrderId {get; set;}
  public Order Order {get; set;}
  public string Product {get;set;}
}

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        base.OnModelCreating(modelBuilder);
    }
}

There is an Order with some lines in the database. When it is loaded it's OrderLines property is null.

I have tried making OrderLines virtual, it did not help. Otherwise, everything is set to default. Lazy load is true, CreateProxy is true...

When I try to Include("OrderLines") it works and fetches the lines from DB.

Upvotes: 2

Views: 1364

Answers (2)

MattSull
MattSull

Reputation: 5564

In OrderLine try placing a FK annotation over the navigation property:

class OrderLine
{
  public Guid Id {get; set;}
  public string Product {get;set;}

  // 1:many with Order
  public virtual Guid OrderId {get; set;}
  [ForeignKey("Id")]
  public virtual Order Order {get; set;}      
}

Upvotes: 2

Dave
Dave

Reputation: 659

Use the data annotations to annotate the foreign key attribute. You don't need to do it with Fluent API anymore.

[ForeignKey("Id")]
public virtual ICollection<OrderLine> OrderLines {get; set;}

I would have thought it would create that by default.

Upvotes: 1

Related Questions