Jens
Jens

Reputation: 25

Entity Framework Setting Navigation Property by Id Issue

I have two classes: Owner and Dog. In the Dog class there is a Navigation Property defined like this:

public class Dog {
    //Other properties
    public int OwnerId { get; set; }
    [ForeignKey("OwnerId")]
    public virtual Owner Owner{ get; set; }
}

I also have the following (example) method

public void SetOwnerOfFirstDog(int ownerId)
{
   //var owner = context.Owners.First(e => e.Id == ownerId);

   var dog = context.Dogs.First();
   dog.OwnerId = ownerId;
   context.SaveChanges();
} 

This all works but when I later use the same db context and look up the same dog entity it's Owner property is null. (When I use another db context it is not null.)

However, if I uncomment the first line in the SetOwnerOfFirstDog method the Owner property will be correctly set. But of course this is an extra query to the database and I'd like to avoid it.

So my question: How can I make sure that the Owner property is correctly filled in when I look it up after I have set the Dog's Owner by Id.

I am using lazy loading.

Upvotes: 0

Views: 781

Answers (1)

Alexander Andreev
Alexander Andreev

Reputation: 28

You can use Include to load related entities

public void SetOwnerOfFirstDog(int ownerId)
{       
   var dog = context.Dogs.Include(x => x.Owner).First();
   dog.OwnerId = ownerId;
   context.SaveChanges();
} 

Upvotes: 1

Related Questions