1
votes

I'm using Entity Framework 4.3.1 and am having some trouble with my navigation properties.

In my context, I've enabled lazy loading:

public MyContainer()
        : base(ConnectionString, ContainerName)
{
    this.ContextOptions.LazyLoadingEnabled = true;
}

Also, I have made the property virtual (actually I generated it from my Model):

public virtual Driver Driver
{
    get { return _driver; }
    set
    {
        if (!ReferenceEquals(_driver, value))
        {
            var previousValue = _driver;
            _driver= value;
            FixupDriver(previousValue);
        }
    }
}
private Driver _driver;

This is in an entity called Ride. However, when I acces myContext.Ride.Driver it is null. This is strange because when I inspect the Ride entity during runtime I can see that the foreign key is actually filled with the ID of the expected Driver.

Is there anything extra I need to do?

When I generate a new Ride, I set the DriverID, but subsequently the Driver from which I get the ID is not automatically added as a Navigation Property.


Okay, I just solved it myself, so I'll share the answer: I needed to Attach the Driver entity back to the context. myContext.Driver.Attach(Driver). Then I could do: Ride.Driver = Driver instead of Ride.DriverID = Driver.DriverID.

In code I'm doing this:

db.Driver.Attach(Driver); // Driver is a public property in my class
myNewRide.Driver = Driver;
db.SaveChanges();
1
Okay, I just solved it myself, so I'll share the answer: I needed to Attach the Driver entity back to the context. myContext.Driver.Attach(Driver). Then I could do: Ride.Driver = Driver instead of Ride.DriverID = Driver.DriverID. - Davio
PLease write this as an answer an mark it, so everybody sees that it is solved, thanks. - Shegit Brahm
:-) almost what I meant. Do you see the "answer field" under your question? I thought to put your solution there, because then you are able to click afterwards "mark as answer". - Shegit Brahm

1 Answers

0
votes

Okay, I just solved it myself, so I'll share the answer: I needed to Attach the Driver entity back to the context. myContext.Driver.Attach(Driver). Then I could do: Ride.Driver = Driver instead of Ride.DriverID = Driver.DriverID