Using EF Core 2.2.3, I have set up Lazy-Loading as per the docs https://learn.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading

Startup:

public void ConfigureServices(IServiceCollection services)
{
    // snipped other stuff

    services.AddScoped<IProductRepository, ProductRepository>();

    services.AddDbContext<ProductsDbContext>(options => {
        options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("ProductsConnection"));
    });
}

Example entity:

public class Product: IEntity
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<ProductIndustry> ProductIndustries { get; set; }
}

Product repository method:

public ServiceResponse<TEntity> GetByIdAsync(Guid id)
{
    try
    {
        var entity = DbContext.Set<TEntity>()
            .AsNoTracking()
            .FirstOrDefault(e => e.Id == id);

        return ServiceResponseFactory.SuccessfulResponse(entity);
    }
    catch (Exception ex)
    {
        LogService.LogException(ex);
        return ServiceResponseFactory.FailedResponse<TEntity>();
    }
}

If I inspect the entity when debugging, my navigation properties show the following error:

((Castle.Proxies.ProductProxy)productResponse.Content).ProductIndustries' threw an exception of type 'System.InvalidOperationException

If I click the reload icon next to the property, the error changes to:

error CS0234: The type or namespace name 'ProductProxy' does not exist in the namespace 'Castle.Proxies' (are you missing an assembly reference?)

I'm retrofitting lazy-loading to an existing project, and I've removed all async code on the DB layer, and I've tried removing .AsNoTracking() as well but this hasn't sorted it.

The documentation on this is really simple, so I'm not sure what I've missed.

1

There are 1 best solutions below

0
On BEST ANSWER

In your entity class, above declaration of the virtual ProductIndustriesProperty, put:

[ForeignKey("ParentId")]

In the quotes put the name of the property on ProductIndustry that is the key to your parent.