title: Cannot use table 'DeviceCodes' for entity type 'DeviceCode' since it is being used for entity type 'DeviceFlowCodes'
body: <p>I am using ASP.NET Core 5 (version <code>5.0.100-rc.2.20479.15</code>); Visual Studio Microsoft Visual Studio Community 2019 Preview - Version 16.8.0 Preview 6.0; Mircosoft SQL Server 2019; Entity Framework Core; ASP.NET Core Identity Server; Blazor web-assembly.</p>
  <p>Libaries</p>
  <pre><code>&lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore&quot; Version=&quot;5.0.0-rc.2.20475.17&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Identity.EntityFrameworkCore&quot; Version=&quot;5.0.0-rc.2.20475.17&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Identity.UI&quot; Version=&quot;5.0.0-rc.2.20475.17&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.ApiAuthorization.IdentityServer&quot; Version=&quot;5.0.0-rc.2.20475.17&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.SqlServer&quot; Version=&quot;5.0.0-rc.2.20475.6&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.Tools&quot; Version=&quot;5.0.0-rc.2.20475.6&quot; /&gt;
  &lt;/ItemGroup&gt;
  </code></pre>
  <p>When application don't query anything to database, it work ok. When I login, has action to database, it catch error.</p>
  <p>In file <code>ApplicationDbContext.cs</code> , I have call base constructor from base class</p>
  <pre class="lang-cs prettyprint-override"><code>public partial class ApplicationDbContext : ApiAuthorizationDbContext&lt;ApplicationUser&gt;
  {
      public ApplicationDbContext(
          DbContextOptions options,
          IOptions&lt;OperationalStoreOptions&gt; operationalStoreOptions) : base(options, operationalStoreOptions)
      {
      }
  
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
          if (!optionsBuilder.IsConfigured)
          {
  #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
              optionsBuilder.UseSqlServer(&quot;Server=DESKTOP-CA6GPT5;Database=foo;User Id=fooUser; Password=SeCrET;Trusted_Connection=True;&quot;);
          }
      }
  
  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
      base.OnModelCreating(modelBuilder);
      // ...
  }
  </code></pre>
  <p>In database, I have</p>
  <p><a href="https://i.stack.imgur.com/f224tm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f224tm.png" alt="enter image description here" /></a></p>
  <p><a href="https://i.stack.imgur.com/l5zB9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l5zB9.png" alt="enter image description here" /></a></p>
  <p><a href="https://i.stack.imgur.com/QcsBx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QcsBx.png" alt="enter image description here" /></a></p>
  <p><a href="https://i.stack.imgur.com/oCXFJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oCXFJ.png" alt="enter image description here" /></a></p>
  <p>Error message:</p>
  <pre><code>An unhandled exception occurred while processing the request.
  InvalidOperationException: Cannot use table 'DeviceCodes' for entity type 'DeviceCode' since it is being used for entity type 'DeviceFlowCodes' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'DeviceCode' on the primary key properties and pointing to the primary key on another entity typed mapped to 'DeviceCodes'.
  Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IReadOnlyList&lt;IEntityType&gt; mappedTypes, string tableName, string schema, IDiagnosticsLogger&lt;Validation&gt; logger)
  </code></pre>
  <p>Detail</p>
  <pre><code>InvalidOperationException: Cannot use table 'DeviceCodes' for entity type 'DeviceCode' since it is being used for entity type 'DeviceFlowCodes' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'DeviceCode' on the primary key properties and pointing to the primary key on another entity typed mapped to 'DeviceCodes'.
  Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IReadOnlyList&lt;IEntityType&gt; mappedTypes, string tableName, string schema, IDiagnosticsLogger&lt;Validation&gt; logger)
  Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IModel model, IDiagnosticsLogger&lt;Validation&gt; logger)
  Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger&lt;Validation&gt; logger)
  Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger&lt;Validation&gt; logger)
  Microsoft.EntityFrameworkCore.Metadata.Conventions.ValidatingConvention.ProcessModelFinalized(IModel model)
  Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ImmediateConventionScope.OnModelFinalized(IModel model)
  Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IModel model)
  Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
  Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
  Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
  Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
  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.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.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.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.Set&lt;TEntity&gt;()
  Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore&lt;TUser, TContext, TKey, TUserClaim, TUserLogin, TUserToken&gt;.get_UsersSet()
  Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore&lt;TUser, TContext, TKey, TUserClaim, TUserLogin, TUserToken&gt;.get_Users()
  Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore&lt;TUser, TContext, TKey, TUserClaim, TUserLogin, TUserToken&gt;.FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken)
  Microsoft.AspNetCore.Identity.UserManager&lt;TUser&gt;.FindByNameAsync(string userName)
  Microsoft.AspNetCore.Identity.SignInManager&lt;TUser&gt;.PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)
  Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Internal.LoginModel&lt;TUser&gt;.OnPostAsync(string returnUrl)
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+GenericTaskHandlerMethod.Convert&lt;T&gt;(object taskAsObject)
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+GenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
  Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
  Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextResourceFilter&gt;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.&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.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
  IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
  IdentityServer4.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
  Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
  IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
  Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
  Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
  Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
  Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  
  Show raw exception details
  System.InvalidOperationException: Cannot use table 'DeviceCodes' for entity type 'DeviceCode' since it is being used for entity type 'DeviceFlowCodes' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'DeviceCode' on the primary key properties and pointing to the primary key on another entity typed mapped to 'DeviceCodes'.
     at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IReadOnlyList`1 mappedTypes, String tableName, String schema, IDiagnosticsLogger`1 logger)
     at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IModel model, IDiagnosticsLogger`1 logger)
     at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
     at Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
     at Microsoft.EntityFrameworkCore.Metadata.Conventions.ValidatingConvention.ProcessModelFinalized(IModel model)
     at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalized(IModel model)
     at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IModel model)
     at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel()
     at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
     at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
     at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
     at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
     at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
     at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.&lt;&gt;c.&lt;TryAddCoreServices&gt;b__7_3(IServiceProvider p)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
     at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
     at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
     at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
     at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
     at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
     at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
     at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
     at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore`6.get_UsersSet()
     at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore`6.get_Users()
     at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore`6.FindByNameAsync(String normalizedUserName, CancellationToken cancellationToken)
     at Microsoft.AspNetCore.Identity.UserManager`1.FindByNameAsync(String userName)
     at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(String userName, String password, Boolean isPersistent, Boolean lockoutOnFailure)
     at Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Internal.LoginModel`1.OnPostAsync(String returnUrl)
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeNextResourceFilter&gt;g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State&amp; next, Scope&amp; scope, Object&amp; state, Boolean&amp; isCompleted)
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
  --- End of stack trace from previous location ---
     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.&lt;InvokeAsync&gt;g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
     at Microsoft.AspNetCore.Routing.EndpointMiddleware.&lt;Invoke&gt;g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
     at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
     at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
     at IdentityServer4.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
     at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  </code></pre>
  <p>How to fix it?</p>