1

I am using EF Core 3.1.7. The DbContext has the UseLazyLoadingProxies set. Fluent API mappings are being used to map entities to the database. I have an entity with a navigation property that uses a backing field. Loads and saves to the database seem to work fine except for an issue when accessing the backing field before I access the navigation property.

It seems that referenced entities don't lazy load when accessing the backing field. Is this a deficiency of the Castle.Proxy class or an incorrect configuration?

Compare the Student class implementation of IsRegisteredForACourse to the IsRegisteredForACourse2 for the behavior in question.

Database tables and relationships. Student and Courses

Student Entity

using System.Collections.Generic;

namespace EFCoreMappingTests
{
    public class Student
    {
        public int Id { get; }
        public string Name { get; }

        private readonly List<Course> _courses;
        public virtual IReadOnlyList<Course> Courses => _courses.AsReadOnly();

        protected Student()
        {
            _courses = new List<Course>();
        }

        public Student(string name) : this()
        {
            Name = name;
        }

        public bool IsRegisteredForACourse()
        {
            return _courses.Count > 0;
        }

        public bool IsRegisteredForACourse2()
        {
            //Note the use of the property compare to the previous method using the backing field.
            return Courses.Count > 0;
        }

        public void AddCourse(Course course)
        {
            _courses.Add(course);
        }
    }
}

Course Entity

namespace EFCoreMappingTests
{
    public class Course
    {
        public int Id { get; }
        public string Name { get; }
        public virtual Student Student { get; }

        protected Course()
        {
        }
        public Course(string name) : this()
        {
            Name = name;
        }
    }
}

DbContext

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace EFCoreMappingTests
{
    public sealed class Context : DbContext
    {
        private readonly string _connectionString;
        private readonly bool _useConsoleLogger;

        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }

        public Context(string connectionString, bool useConsoleLogger)
        {
            _connectionString = connectionString;
            _useConsoleLogger = useConsoleLogger;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
            {
                builder
                    .AddFilter((category, level) =>
                        category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                    .AddConsole();
            });

            optionsBuilder
                .UseSqlServer(_connectionString)
                .UseLazyLoadingProxies(); 

            if (_useConsoleLogger)
            {
                optionsBuilder
                    .UseLoggerFactory(loggerFactory)
                    .EnableSensitiveDataLogging();
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>(x =>
            {
                x.ToTable("Student").HasKey(k => k.Id);
                x.Property(p => p.Id).HasColumnName("Id");
                x.Property(p => p.Name).HasColumnName("Name");
                x.HasMany(p => p.Courses)
                    .WithOne(p => p.Student)
                    .OnDelete(DeleteBehavior.Cascade)
                    .Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);
            });
            modelBuilder.Entity<Course>(x =>
            {
                x.ToTable("Course").HasKey(k => k.Id);
                x.Property(p => p.Id).HasColumnName("Id");
                x.Property(p => p.Name).HasColumnName("Name");
                x.HasOne(p => p.Student).WithMany(p => p.Courses);
                
            });
        }
    }
}

Test program which demos the issue.

using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Linq;

namespace EFCoreMappingTests
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = GetConnectionString();

            using var context = new Context(connectionString, true);

            var student2 = context.Students.FirstOrDefault(q => q.Id == 5);

            Console.WriteLine(student2.IsRegisteredForACourse());
            Console.WriteLine(student2.IsRegisteredForACourse2()); // The method uses the property which forces the lazy loading of the entities
            Console.WriteLine(student2.IsRegisteredForACourse());
        }

        private static string GetConnectionString()
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            return configuration["ConnectionString"];
        }
    }
}

Console Output

False
True
True
J Swanson
  • 71
  • 1
  • 6

1 Answers1

0

When you declare a mapped property in an EF entity as virtual, EF generates a proxy which is capable of intercepting requests and assessing whether the data needs to be loaded. If you attempt to use a backing field before that virtual property is accessed, EF has no "signal" to lazy load the property.

As a general rule with entities you should always use the properties and avoid using/accessing backing fields. Auto-initialization can help:

public virtual IReadOnlyList<Course> Courses => new List<Course>().AsReadOnly();
Steve Py
  • 26,149
  • 3
  • 25
  • 43
  • It makes sense about the virtual property being the "signal" to lazy load. The problem with the auto-initialization suggestion is that internal to the class I still need the ability to add to the collection, but externally it should be read only. See the Student class's AddCourse method for an example. – J Swanson Aug 13 '20 at 13:22
  • Then it shouldn't be readonly, just a virtual ICollection. Entities should reflect the data domain of your system so it is unusual to try and enforce rules like read-only unless that data state truly cannot be altered in the scope of that context. Enforcement like that is usually part of a pattern like DDD where you would use bounded contexts. Where you have a context that is responsible for reading/querying, the Courses could be readonly, where another bounded context for editing students and associating courses would use an ICollection domain. Viewmodels and such can restrict operations. – Steve Py Aug 14 '20 at 00:01
  • The goal of the design to have a rich domain model that would support DDD. I am no expert at DDD, but it seems the suggestion of a bounded context is not completely accurate. A rich domain model naturally should be able to both query and execute commands. Back to the original question. It seems then this is how the Castle.Proxy works by triggering only on the property and not both the property and the backing field. I guess my other option is to skip the lazy loading and always eager load everything. Any other suggestions? – J Swanson Aug 16 '20 at 01:27
  • Where I would have backing fields for properties or dependencies I follow a simple rule that the only code that accesses them is the property. I use underscore notation for private members so they are easy to spot in the code. If I do a find usages on any field it is easy to determine who might have used it and cover off with the other developers. Ultimately you have to trust the people you work with to understand and adopt a best practice. I would not use backing fields for collections. They are either mutable or they are not. – Steve Py Aug 16 '20 at 01:49