1

I have project in Entity Framework Core 3.1. When I use lazy loading like this:

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

and I call this:

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

    }

I got this error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Microsoft.EntityFrameworkCore.ModelExtensions.FindEntityType(...) returned null.

But when I remove the UseLazyLoadingProxies(), everything works. Any ideas what can be wrong or how to fix it?

2 Answers 2

1

Most likely the passed object entity is a proxy instance, in which case GetType() won't be a registered entity type.

Consider replacing FindEntityType with FindRuntimeEntityType:

Gets the entity that maps the given entity class, where the class may be a proxy derived from the actual entity type.

Sign up to request clarification or add additional context in comments.

Comments

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
}

1 Comment

How does this answer the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.