0
votes

I have defined two classes with a one-to-many foreign key relation, generated by the Entity Framework 6.0 database first.

public class car
{
    public Nullable<int> label_id { get; set; }
    public virtual label label { get; set; }
}

public class label
{
    public virtual ObservableCollection<car> cars { get; set; }
}

I create a proxy object and add it to DBContext.

 car c = _context.cars.Create();
_context.cars.Add(c);

Then I set a foreign key property and try to access the corresponding navigation property.

c.label_id = 4;
label l = c.label;

Setting the foreign key property label_id doesn't load the navigation property label. The last line in the code returns null.

The classes follow the requirements set out here Requirements for Creating POCO Proxies (Debugging shows a proxy car object is created so I believe all requirements were satisfied).

The database table label holds an item with a primary key of 4.

I am not calling SaveChanges or DetectChanges here because I think I should not need to do so.

This documentation How to: Use Lazy Loading to Load Related Objects says that "With lazy loading enabled, related objects are loaded when they are accessed through a navigation property".

I haven't disabled lazy loading, I have a proxy object at hand but the navigation property is not loaded when I try to access it.

What can be the reason?

1

1 Answers

0
votes

I'm not sure if you can get the lazy loading for an object without first saving your changes (never tried it, or trusted it). However, have you checked if the lazy loading options is set to true? I'm sure it is, but I'm asking the simple questions first.

var lazyLoadingIsTrue = _context.ContextOptions.LazyLoadingEnabled == true;