question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

"Foreign keys are both mapped to <Table> but referencing different principal tables" on long entity names

See original GitHub issue

Ask a question

I’m getting this exception:

Error: System.InvalidOperationException: The foreign keys {'AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongDetailsId'} on 'Location' and {'AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongOwnerEntityId'} on 'AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongDetails' are both mapped to 'AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongDet~.FK_AReallyReallyReallyReallyReallyReallyReallyReallyReallyLong~' but referencing different principal tables ('AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongDet~' and 'Owners').

This seems to arise there’s a one-to-many relationship, with an owned type on the one side, and when the entity names are long enough to cause that ~ to show up in the error. I think it’s checking only the first part of the name for equivalence.

Include your code

  [Owned]
  public class Location
  {
    public float Long { get; set; }
    public float Lat { get; set; }
  }


  public class AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongOwnerEntity
  {
    public int Id { get; set; }
    public IQueryable<AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongDetails> Details { get; set; }
  }

  public class AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongDetails
  {
    public int Id { get; set; }
    public int OwnerId { get; set; }
    public virtual Location Location { get; set; }
  }

  public class DataContext : DbContext
  {
    public virtual DbSet<AReallyReallyReallyReallyReallyReallyReallyReallyReallyLongOwnerEntity> Owners { get; set; }
  }

Include stack traces

at Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalForeignKeyExtensions.AreCompatible(IForeignKey foreignKey, IForeignKey duplicateForeignKey, StoreObjectIdentifier& storeObject, Boolean shouldThrow)
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateCompatible(IForeignKey foreignKey, IForeignKey duplicateForeignKey, String foreignKeyName, StoreObjectIdentifier& storeObject, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedForeignKeysCompatibility(IReadOnlyList`1 mappedTypes, StoreObjectIdentifier& storeObject, 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 Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.NpgsqlModelValidator.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.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
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.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
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.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
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.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_Dependencies()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureDeleted()
at FSI_0005.scrub()
at <StartupCode$FSI_0006>.$FSI_0006.main@()

Include provider and version information

EF Core version: 5.0.8 Database provider: Npgsql.EntityFrameworkCore.PostgreSQL 5.0.8 Target framework: .NET 5.0 Operating system: Windows 10 Pro 21H1 (19043.1110) IDE: Visual Studio 2019

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Arminkhodaeicommented, May 25, 2022

I encountered this problem and this was the reason in my case:

There’s a limit to the length of identifiers depending on the underlying database. In my case (postgres) the identifiers length is limited to 63 bytes by default and the issue occurs as auto generated table names from the owned types can exceed this limits.

Solution: I solved the issue by simply setting a custom and shorter table name on the owned collection.

References: PostgreSQL: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS

SQLServer: https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers?view=sql-server-ver16#classes-of-identifiers

0reactions
RyanGaudioncommented, Jun 16, 2022

@Arminkhodaei thank you for your reply - that was the issue for me too. Using PostgresSQL provider, if my table names are too long I get this error

Read more comments on GitHub >

github_iconTop Results From Across the Web

"Foreign keys are both mapped to <Table> but referencing ...
"Foreign keys are both mapped to <Table> but referencing different principal tables" on long entity names #28488.
Read more >
EF Core - Self referencing relationship with custom foreign ...
I am trying to use a custom foreign key and principal key that are not mapped to a real database columns. With the...
Read more >
Relationships, navigation properties, and foreign keys - EF6
In relational databases, relationships (also called associations) between tables are defined through foreign keys. A foreign key (FK) is a ...
Read more >
Advanced table mapping - EF Core
EF Core allows to map two or more entities to a single row. This is called table splitting or table sharing. Configuration. To...
Read more >
DataAnnotations - ForeignKey Attribute in EF 7 & EF Core
The ForeignKey attribute is used to configure a foreign key in the relationship between two entities in EF 6 and EF Core. It...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found