2

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?

3
  • What happens if you mark your User property in Vacation entity with [ForeignKey("UserUsername")]? Commented Mar 18, 2012 at 22:03
  • @LadislavMrnka I've done the mapping by overriding OnModelCreating method of dbContext Commented Mar 18, 2012 at 22:12
  • I have worked this out and will post answer in 6 hours due to rep. Commented Mar 18, 2012 at 22:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can you please show me the example. I face this problem as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.