实体框架核心和延迟加载问题

时间:2020-04-17 10:13:11

标签: c# entity-framework asp.net-core .net-core entity-framework-core

我在Entity Framework Core 3.1中有项目。当我使用像这样的延迟加载时:

setData()

我称之为:

services.AddDbContext<IQContext>(options => options.UseLazyLoadingProxies().UseSqlServer(...)

我收到此错误:

 public async Task<Guid> UpdateAsync(object entity ...)
    {
...
      Type entityType = entity.GetType();
      string primaryKeyName = _dbContext.Model.FindEntityType(entityType).FindPrimaryKey().Properties.Select(x => x.Name).Single();

    }

但是当我删除System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.EntityFrameworkCore.ModelExtensions.FindEntityType(...) returned null. 时,一切正常。 有什么想法是错误的或如何解决?

2 个答案:

答案 0 :(得分:0)

传递的object entity很可能是代理实例,在这种情况下GetType()不会是注册实体类型。

考虑将FindEntityType替换为FindRuntimeEntityType

获取映射给定实体类的实体,其中该类可以是从实际实体类型派生的代理。

答案 1 :(得分:0)

package-install: Microsoft.EntityFrameworkCore.Proxies

public void ConfigureServices(IServiceCollection services)
{
    #region Database configuration

    // Database configuration
    services.AddDbContext<DbContext>(options =>
        options.UseLazyLoadingProxies()
            .UseSqlServer(Configuration.GetConnectionString("MyConnectionString")));

    #endregion Database configuration
}