title: Entity Framework Core Problem with Scaffolding entity with foreign key constraint
body: <p>Hi I scaffold DbContext from existing database using EF Core. The result context contains 2 related entities in <code>OnModelCreating(..)</code> like this:</p>
  <pre><code>modelBuilder.Entity&lt;MauYdc&gt;(entity =&gt;
              {
                  entity.HasNoKey();
  
                  entity.ToTable(&quot;MauYDC&quot;);
  
                  entity.HasIndex(e =&gt; e.Idphieu)
                      .HasName(&quot;IX_MauYDC&quot;)
                      .IsUnique();
  
                  entity.Property(e =&gt; e.Idphieu)
                      .HasColumnName(&quot;IDphieu&quot;)
                      .HasColumnType(&quot;numeric(18, 0)&quot;)
                      .ValueGeneratedOnAdd();
  
                  entity.Property(e =&gt; e.Manv).HasMaxLength(50);
  
                  entity.Property(e =&gt; e.Tenphieu)
                      .HasColumnName(&quot;tenphieu&quot;)
                      .HasMaxLength(100);
              });
  
  modelBuilder.Entity&lt;MauYdcChiTiet&gt;(entity =&gt;
              {
                  entity.HasNoKey();
  
                  entity.ToTable(&quot;MauYDC_ChiTiet&quot;);
  
                  entity.Property(e =&gt; e.Id)
                      .HasColumnName(&quot;ID&quot;)
                      .HasColumnType(&quot;numeric(18, 0)&quot;)
                      .ValueGeneratedOnAdd();
  
                  entity.Property(e =&gt; e.Idphieu)
                      .HasColumnName(&quot;IDphieu&quot;)
                      .HasColumnType(&quot;numeric(18, 0)&quot;);
  
                  entity.Property(e =&gt; e.Idthuoc).HasColumnName(&quot;idthuoc&quot;);
  
                  entity.Property(e =&gt; e.Soluong).HasColumnName(&quot;soluong&quot;);
  
                  entity.HasOne(d =&gt; d.IdphieuNavigation)
                      .WithMany()
                      .HasPrincipalKey(p =&gt; p.Idphieu)
                      .HasForeignKey(d =&gt; d.Idphieu)
                      .OnDelete(DeleteBehavior.Cascade)
                      .HasConstraintName(&quot;FK_MauYDC_chitiet_MauYDC&quot;);
              });
  </code></pre>
  <p>Entity <code>MauYdc</code></p>
  <pre><code>public partial class MauYdc
      {
          public decimal Idphieu { get; set; }
          public string Tenphieu { get; set; }
          public string Manv { get; set; }
      }
  </code></pre>
  <p>Entity <code>MauYdcChiTiet</code></p>
  <pre><code>public partial class MauYdcChiTiet
      {
          public decimal? Idphieu { get; set; }
          public int? Idthuoc { get; set; }
          public double? Soluong { get; set; }
          public decimal Id { get; set; }
  
          public virtual MauYdc IdphieuNavigation { get; set; }
      }
  </code></pre>
  <p>Those are completely generated by EF Core and I leave them untouched. However, I encounter this error when using other table from the context not related to those two</p>
  <pre><code>NullReferenceException: Object reference not set to an instance of an object.
  Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.SetOrAddForeignKey(ForeignKey foreignKey, InternalEntityTypeBuilder principalEntityTypeBuilder, IReadOnlyList&lt;Property&gt; dependentProperties, Key principalKey, string navigationToPrincipalName, Nullable&lt;bool&gt; isRequired, Nullable&lt;ConfigurationSource&gt; configurationSource)
  Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.CreateForeignKey(InternalEntityTypeBuilder principalEntityTypeBuilder, IReadOnlyList&lt;Property&gt; dependentProperties, Key principalKey, string navigationToPrincipalName, Nullable&lt;bool&gt; isRequired, ConfigurationSource configurationSource)
  Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasRelationship(EntityType targetEntityType, Nullable&lt;MemberIdentity&gt; navigationToTarget, Nullable&lt;MemberIdentity&gt; inverseNavigation, bool setTargetAsPrincipal, ConfigurationSource configurationSource, Nullable&lt;bool&gt; required)
  Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder.HasRelationship(EntityType targetEntityType, MemberInfo navigationProperty, ConfigurationSource configurationSource, bool setTargetAsPrincipal)
  Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder&lt;TEntity&gt;.HasOne&lt;TRelatedEntity&gt;(Expression&lt;Func&lt;TEntity, TRelatedEntity&gt;&gt; navigationExpression)
  Hl7Map.Infrastructure.SqlServer.NgoaiTru.NgoaiTruContext+&lt;&gt;c.&lt;OnModelCreating&gt;b__322_31(EntityTypeBuilder&lt;MauYdcChiTiet&gt; entity) in NgoaiTruContext.cs
  +
                  entity.HasOne(d =&gt; d.IdphieuNavigation)
  Microsoft.EntityFrameworkCore.ModelBuilder.Entity&lt;TEntity&gt;(Action&lt;EntityTypeBuilder&lt;TEntity&gt;&gt; buildAction)
  Hl7Map.Infrastructure.SqlServer.NgoaiTru.NgoaiTruContext.OnModelCreating(ModelBuilder modelBuilder) in NgoaiTruContext.cs
  +
              modelBuilder.Entity&lt;MauYdcChiTiet&gt;(entity =&gt;
  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+&lt;&gt;c.&lt;TryAddCoreServices&gt;b__7_3(IServiceProvider p)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor&lt;TArgument, TResult&gt;.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&lt;TArgument, TResult&gt;.VisitCallSite(ServiceCallSite callSite, TArgument argument)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor&lt;TArgument, TResult&gt;.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&lt;TArgument, TResult&gt;.VisitCallSite(ServiceCallSite callSite, TArgument argument)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine+&lt;&gt;c__DisplayClass1_0.&lt;RealizeService&gt;b__0(ServiceProviderEngineScope scope)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
  Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
  Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
  Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService&lt;T&gt;(IServiceProvider provider)
  Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
  Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
  Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
  Microsoft.EntityFrameworkCore.DbContext.get_Model()
  Microsoft.EntityFrameworkCore.Internal.InternalDbSet&lt;TEntity&gt;.get_EntityType()
  Microsoft.EntityFrameworkCore.Internal.InternalDbSet&lt;TEntity&gt;.CheckState()
  Microsoft.EntityFrameworkCore.Internal.InternalDbSet&lt;TEntity&gt;.get_EntityQueryable()
  Microsoft.EntityFrameworkCore.Internal.InternalDbSet&lt;TEntity&gt;.System.Linq.IQueryable.get_Provider()
  System.Linq.Queryable.Where&lt;TSource&gt;(IQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, bool&gt;&gt; predicate)
  Hl7Map.Manager.Administration.PatientManager.Get(string IdBenhNhan) in PatientManager.cs
  +
              var tttn= _myContext.MyOtherTable.Where(ttTiepnhan =&gt; ttTiepnhan.MaBn == IdBenhNhan)?.FirstOrDefault();
  Hl7Map.Areas.FHIR.Controllers.PatientsController.Get(string idBn) in PatientsController.cs
  +
              var pt = await _patientManager.Get(idBn);
  lambda_method(Closure , object )
  Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
  Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
  System.Threading.Tasks.ValueTask&lt;TResult&gt;.get_Result()
  System.Runtime.CompilerServices.ValueTaskAwaiter&lt;TResult&gt;.GetResult()
  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeActionMethodAsync&gt;g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask&lt;IActionResult&gt; actionResultValueTask)
  Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.&lt;InvokeNextActionFilterAsync&gt;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.&lt;InvokeFilterPipelineAsync&gt;g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
  Microsoft.AspNetCore.Routing.EndpointMiddleware.&lt;Invoke&gt;g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
  Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
  Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  </code></pre>
  <p>I already use lazy loading for EF Core:</p>
  <pre><code>services.AddDbContext&lt;MyContext&gt;(options =&gt;
                  options.UseLazyLoadingProxies().UseSqlServer(config.GetConnectionString(&quot;MyConnectionString&quot;))
              );
  </code></pre>
  <p>Debug shows the program stuck while running Context constructor and entity builder ==&gt; so it didn't even reach the <code>Where()</code> expression, so add ? after <code>Where(..)</code> won't fix.</p>
  <p>What is the problem with EF Core? I'm stuck for this so long.</p>