2
votes

I followed the example here

https://docs.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading

And my two classes look like this

  public class RefMedSchool
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }


    public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
}


 public class ApplicationUser : IdentityUser
{
    public string UserFirstName { get; set; }
    public string UserLastName { get; set; }
    public bool MustChangePassword { get; set; }


    public int? MedicalSpecialtyId { get; set; }
    [ForeignKey("RefMedicalSpecialtyForeignKey")]
    public RefMedicalSpecialty RefMedicalSpecialty { get; set; }


    public int RefMedSchoolId { get; set; }
    public virtual RefMedSchool RefMedSchool { get; set; }


    public UserProfileData UserProfileData { get; set; }


    public ICollection<UserFeedback> UserFeedbacks { get; set; }


    public ICollection<UserAction> UserActions { get; set; }


    public ICollection<UserProgram> UserPrograms { get; set; }
}

But when the database tries to be created I get the error below. Whats wrong ? The properties are virtual as needed.

System.InvalidOperationException: 'Navigation property 'RefMedicalSpecialty' on entity type 'ApplicationUser' is not virtual. UseLazyLoadingProxies requires all entity types to be public, unsealed, have virtual navigation properties, and have a public or protected constructor.'

1

1 Answers

7
votes

Entity Framework Core 2.1 introduced lazy loading. It requires all navigation properties to be virtual as explained in the issue Lazy-loading proxies: allow entity types/navigations to be specified:

Currently when lazy-loading proxies are used every entity type in the model must be suitable to proxy and all navigations must be virtual. This issue is about allowing some entity types/navigations to be lazy-loaded while others are not.

The issue is still open and has no resolution, so your desired scenario still isn't supported.

And as the exception tells you:

UseLazyLoadingProxies requires all entity types to be public, unsealed, have virtual navigation properties, and have a public or protected constructor.

So, change all navigation properties (i.e. properties that refer to other entities) to be virtual.

Or use ILazyLoader as explained in Lazy-loading without proxies:

public class Blog
{
    private ICollection<Post> _posts;

    public Blog()
    {
    }

    private Blog(ILazyLoader lazyLoader)
    {
        LazyLoader = lazyLoader;
    }

    private ILazyLoader LazyLoader { get; set; }

    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Post> Posts
    {
        get => LazyLoader?.Load(this, ref _posts);
        set => _posts = value;
    }
}