EntityFrameworkCore.Jet icon indicating copy to clipboard operation
EntityFrameworkCore.Jet copied to clipboard

Navigation Properties not working

Open ITDancer13 opened this issue 7 years ago • 3 comments

The Lazy-Loading or Loading of the navigation properties in general is not working properly.

I used your tutorial from your wiki-page to create the model and the database. All worked fine. Then I modified your code-snipped from section "Use Your Model" to add a blog with one associated post:

static void Main(string[] args)
{
  using (var db = new BloggingContext())
  {
    var blog = new Blog {Url = "http://myblog.com"};
    db.Blogs.Add(blog);
    var post = new Post {Blog = blog, Title = "First Post", Content = "Hello World"};
    db.Posts.Add(post);

    db.SaveChanges();
  }

  using (var db = new BloggingContext())
  {
    foreach (var cBlog in db.Blogs)
    {
      Console.WriteLine(cBlog.Url);
      foreach (var cBlogPost in cBlog.Posts)
      {
        Console.WriteLine(" --> " + cBlogPost.Title + " - " + cBlogPost.Content);
      }
    }
  }
}

When I execute it, I get the following exception at line foreach (var cBlogPost in cBlog.Posts):

System.NullReferenceException: AccessEFCore.Blog.Posts.get returns null.

But when I open the database in Microsoft Access everything looks good. There is one Blog and one Post with the right Keys inside.

ITDancer13 avatar Nov 02 '17 09:11 ITDancer13

It's not a provider issue. Actually Entity Framework Core does not support lazy load. https://blogs.msdn.microsoft.com/dotnet/2017/08/14/announcing-entity-framework-core-2-0/ If you need lazy load you need to use EF 6.2.

Probably the tutorial is from JetEntityFrameworkProvider that is EF 6.x provider. Could you send me a link of the tutorial?

bubibubi avatar Nov 02 '17 13:11 bubibubi

Thank you for your fast answer. The tutorial is okay, I added the lines in which I wanted to get the Posts from the Blog. So it was my fault.

I tried it with JetEntityFrameworkProvider and EF 6.2 too. According to your YouTube-Tutorial I created the Person-Car-Sample-Code.

It worked for me with eager loading :)

using (var context = new Context())
{
  foreach (var person in context.People.Include("OwenedCars"))
  {
    Console.WriteLine(person.Name);
    foreach (var personOwenedCar in person.OwenedCars)
    {
      Console.WriteLine("--> " + personOwenedCar.Name);
    }
  }
}

But when I remove .Include("OwenedCars") in the first foreach-loop, I didn´t get any cars in the second loop.

ITDancer13 avatar Nov 02 '17 14:11 ITDancer13

Did you mark Person.OwenedCars as virtual?

bubibubi avatar Nov 02 '17 20:11 bubibubi