Why is the navigation property not populated when its class is private?

I have this simple model:

class Parent
{
   public int Id { get; set; }

   public virtual ICollection<Child> Children { get; set; }
}

class Child
{
   public int Id { get; set; }
   public int ParentId { get; set; }

   public virtual Parent Parent { get; set; }
}

class MyContext : DbContext
{
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Children { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Child>().HasRequired(s => s.Parent).WithMany(s => s.Children).HasForeignKey(s => s.ParentId);

        base.OnModelCreating(modelBuilder);
    }
}

And when I use MyContext, as shown below, I get a link reference exception because it child.Parentis null

var context = new MyContext();
var child = context.Children.First();
var parentId = child.Parent.Id;              // Parent == null

To solve this problem, I need to change the class access modifier Parentand Childhow public.

Why is this required? Or is it just a mistake?

+4
source share
2 answers

, Entity Framework Lazy Loading, . , public. , , , EF - , - . , , virtual, , EF -.

msdn, EF.

+4

-, -: private, internal. ( ) (. MSDN ).

-, Lazy Loading . Octaviocci, Lazy Loading, : . virtual, EF, . , () virtual. , , Include .

var context = new MyContext();
var child = context.Children.Include(c => c.Parent).First();
var parentId = child.Parent.Id;
+2

Source: https://habr.com/ru/post/1625126/


All Articles