NullReferenceException: Object reference not set to an instance of an object. Entity Framework Core 3.1

Michael Mastro II
26
Reputation points
I have the above error showing in Visual Studio 2019. The project is built on a Asp.Net Core 3.1 and EF Core 3.1, and the version in my QA environment is not demonstrating the errors. The only changes I made were to add Authentication and Authorization to the controllers. I did not change the DatabaseContext model or the database. So I am not sure why I am continually getting the error.
Here is the error:
modelBuilder.Entity<ViewModelClass.Dtl.Models.FactionViewModels.FactionViewModel>(query => {
query.Ignore( q => q.FactionNames );
query.Ignore( q => q.ReputationLevels );
query.Ignore( q => q.ReputationTypes );
query.HasNoKey();
} );
NullReferenceException: Object reference not set to an instance of an object.
Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RequiredAttributeOnCollection(IDiagnosticsLogger<Model> diagnostics, INavigation navigation)
Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RequiredAttributeOnCollection(IDiagnosticsLogger<Model> diagnostics, INavigation navigation)
Microsoft.EntityFrameworkCore.Metadata.Conventions.RequiredNavigationAttributeConvention.ProcessNavigationAdded(IConventionRelationshipBuilder relationshipBuilder, IConventionNavigation navigation, RequiredAttribute attribute, IConventionContext<IConventionNavigation> context)
Microsoft.EntityFrameworkCore.Metadata.Conventions.NavigationAttributeConventionBase<TAttribute>.ProcessNavigationAdded(IConventionRelationshipBuilder relationshipBuilder, IConventionNavigation navigation, IConventionContext<IConventionNavigation> context)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ImmediateConventionScope.OnNavigationAdded(IConventionRelationshipBuilder relationshipBuilder, IConventionNavigation navigation)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+RunVisitor.VisitOnNavigationAdded(OnNavigationAddedNode node)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+OnNavigationAddedNode.Accept(ConventionVisitor visitor)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ConventionVisitor.Visit(ConventionNode node)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ConventionVisitor.VisitConventionScope(ConventionScope node)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ConventionBatch.Run()
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ConventionBatch.Dispose()
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ImmediateConventionScope.OnEntityTypeAdded(IConventionEntityTypeBuilder entityTypeBuilder)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnEntityTypeAdded(IConventionEntityTypeBuilder entityTypeBuilder)
Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(EntityType entityType)
Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(Type type, ConfigurationSource configurationSource)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(ref TypeIdentity type, ConfigurationSource configurationSource, Nullable<bool> shouldBeOwned)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(Type type, ConfigurationSource configurationSource, Nullable<bool> shouldBeOwned)
Microsoft.EntityFrameworkCore.ModelBuilder.Entity<TEntity>()
Microsoft.EntityFrameworkCore.ModelBuilder.Entity<TEntity>(Action<EntityTypeBuilder<TEntity>> buildAction)
Lotro.EntityClass.Dal.Models.LotroModel.OnModelCreating(ModelBuilder modelBuilder) in LotroModel.cs
+
modelBuilder.Entity<ViewModelClass.Dtl.Models.FactionViewModels.FactionViewModel>(query => {
Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder+<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider provider)
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
Microsoft.EntityFrameworkCore.DbContext.Set<TEntity>()
Lotro.WebAppMVC.Controllers.ServersController.Index() in ServersController.cs
+
public IActionResult Index() => View( _db.Set<ServerViewModel>().FromSqlRaw( sql: "SELECT Server_ID AS ServerID, Server_Name AS ServerName FROM dbo.Server WHERE ActiveRecord = 1 ORDER BY Server_Name" ).ToList() );
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Does anyone see a reason why this is now broken?
Thanks in advance.
{count} votes
I put a breakpoint at a similar entity in the DbContext and then Stepped Into entity with no problem, I put a breakpoint at two entities prior to this view model, and even though the are just HasNoKey, I was able to step through those entities. Immediately upon hitting the FactionViewModel entity it threw the NullReferenceException, it wouldn't even allow me to step into it.
I pulled my code down from the source, which I triggered a release to the staging server prior to grabbing to code. It still works on the Staging server as is. It does not work in the other computer either now. And this is without the Authentication / Authorization code on it. If I comment out the entity from the DbContext model, it get though and I am able to get past there and work the controllers. I verified that I am still using 3.1.2 for EF Core on the class library.
The only difference between when I committed this code and pushed it both Staging then Production is that I have moved from Visual Studio 2017 to Visual Studio 2019. I have not updated any packages, that this project uses, to be newer than 3.1.2.
I find this strange that it is now broken, but was working correctly when it was committed.
Can you clarify? What does "hitting the FactionViewModel entity" mean? FactionViewModel is null and whatever populates the FactionViewModel should never return null? Also, by definition, a View Model is a model for a view which populates the UI not an entity. Can you explain or show how how FactionViewModel is populated? Are you executing a raw SQL query?
If you still have VS2017, does the code not throw an exception?
VS2019 does not change behavior when there are zero code changes between loading in VS2017 to VS2019 and VS2019 to VS2017 unless there have been code changes e.g. using something available in C#9 but that is not the case here?
I am executing raw sql against the ViewModels, as there are quite a few stored procedures that were already in the database prior to developing the MVC application. I put a break point at CraftClassViewModel and was able to step into it and then a breakpoint at FactionListViewModel, I stepped to the FactionViewModel when it threw the error. See snip of my dbcontext.
In my dbcontext:
modelBuilder.Entity<ViewModelClass.Dtl.Models.CraftClassViewModels.CraftClassViewModel>(query => {
query.Ignore( q => q.Crafts );
query.Ignore( q => q.ReputationType );
query.HasNoKey();
} );
Here is the ViewModel itself:
Here is from the controller:
public async Task<IActionResult> Edit( int? id )
{
This is one of the many times it is used,
Here is from the controller:
public async Task<IActionResult> Edit( int? id )
{
This is one instance of where it is used.
No I do not have access to V.S. 2017 at this time. Is it possible that for some reason other tools are interfering? I have the .Net 5 SDK installed on the machine, and for another project had to update my ef tools to 5.0.5. Even though I still have the .Net 3.1 SDK installed.
FactionViewModel is configured in the Dd context as if the FactionViewModel structure is returned from a query. But that is not how FactionViewModel is used. The object members within the FactionViewModel are populated from queries while FactionViewModel is instantiated in code.
Remove the FactionViewModel registration from the Db context. FactionViewModel is not an entity.
In my opinion, the naming convention is confusing. View models are simple objects used by a View to render HTML or a container for parameters passed from an HTML form to an Action. You're using the term view model as both a view model and an entity. I think that's where the confusing is coming from.
Removing it has worked. The problem is I had to add all the ViewModels to the DbContext, including the FactionViewModel to get it to work previously. It is working in Visual Studio and since I pushed that to the Staging server it seems to work there.
Doubtful
This means it's not a code issue but more likely a permission issue
Sign in to comment
Activity