【问题标题】:Entity Framework Core and Lazy loading problem实体框架核心和延迟加载问题
【发布时间】:2020-04-17 10:13:11
【问题描述】:

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

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.

但是当我删除 UseLazyLoadingProxies() 时,一切正常。 有什么想法可能是错误的或如何解决?

【问题讨论】:

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


    【解决方案1】:

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

    考虑将FindEntityType 替换为FindRuntimeEntityType

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

    【讨论】:

      【解决方案2】:
      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
      }
      

      【讨论】:

      • 这如何回答这个问题?
      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      相关资源
      最近更新 更多