Question

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();
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top