Tom Miller
Tom Miller

Reputation: 435

Entity framework null reference on foreign key object

I'm using Entity Framework Code First v 4.3.0

I have a two entities with a one to many relationship

e.g.

  public class User
  {
    [Key]
    public virtual string Username { get; set; }

    public virtual ICollection<Vacation> Vacations { get; set; }
  }

  public class Vacation
  {
    public int Id { get; set; }

    public virtual User User { get; set; }

    public virtual string UserUsername { get; set; }

  }

So the scenario is a User is created with a username of "User1". Subsequently a Vacation is created with the UserUsername field set to "User1". So we have our relationship.

If I then query the database after the Vacation is saved for the new Vacation User is null.

If I dispose of the DbContext and new it up. Requery for the Vacation User is set.

Any ideas why this might be?

Upvotes: 2

Views: 2831

Answers (1)

Tom Miller
Tom Miller

Reputation: 435

OK let me try and explain what the problem was.

Microsoft say that If lazy loading is enabled and a related entity is already loaded, it won't be loaded again.

I assume it's this design that is causing me problems.

I create my new Vacation, set UserUsername to "User1" and hit save. I then query the DbContext for the new vacation. Since this entity is already loaded within the context of my DbContext it isn't reloaded hence why User is null.

If I created a new DbContext and ran the same query User is populated.

I hope this makes sense.

Upvotes: 2

Related Questions