EF Core 延迟加载 - 导航属性失败 "The type or namespace name 'ProductProxy' does not exist in the namespace 'Castle.Proxies'"

EF Core Lazy-Loading - Navigation properties fail with "The type or namespace name 'ProductProxy' does not exist in the namespace 'Castle.Proxies'"

使用 EF Core 2.2.3,我根据文档设置了延迟加载 https://docs.microsoft.com/en-us/ef/core/querying/related-data#lazy-loading

启动:

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

    services.AddScoped<IProductRepository, ProductRepository>();

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

示例实体:

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

    public string Name { get; set; }

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

产品存储库方法:

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>();
    }
}

如果我在调试时检查实体,我的导航属性会显示以下错误:

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

如果我单击 属性 旁边的重新加载图标,错误将更改为:

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

我正在对现有项目进行延迟加载改造,我已经删除了数据库层上的所有异步代码,我也尝试删除 .AsNoTracking() 但这还没有解决。

这方面的文档非常简单,所以我不确定我错过了什么。

在您的实体 class 中,虚拟 ProductIndustriesProperty 的声明上方, 放:

[ForeignKey("ParentId")]

在引号中输入 ProductIndustry 上 属性 的名称,这是您父级的密钥。