Entity Framework Core Error

Asked

Viewed 967 times

1

I have an error with Entity Framework core when I add Migration, the following error appears to me:

    System.InvalidOperationException: Cannot use table 'Atleta' for entity type 'Pessoa' since it is being used for entity type 'Atleta' and there is no relationship between the primary key {'PessoaId'} and the primary key {'AtletaId'}.
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IReadOnlyList`1 mappedTypes, String tableName)
   at Microsoft.EntityFrameworkCore.Internal.SqlServerModelValidator.ValidateSharedTableCompatibility(IReadOnlyList`1 mappedTypes, String tableName)
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IModel model)
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model)
   at Microsoft.EntityFrameworkCore.Internal.SqlServerModelValidator.Validate(IModel model)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__0(Object k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.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.DatabaseFacade.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_DatabaseCreator()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
   at acme.one.ride.infra.Config.Context..ctor(DbContextOptions`1 connString) in C:\Users\linne\source\repos\acme.one.ride\acme.one.ride.infra\Config\Context.cs:line 14
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_2.<FindContextTypes>b__11()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Cannot use table 'Atleta' for entity type 'Pessoa' since it is being used for entity type 'Atleta' and there is no relationship between the primary key {'PessoaId'} and the primary key {'AtletaId'}.

My classes are like this: Person:

    public class Pessoa : IPessoa
{

    public Pessoa()
    {
        VideosPessoas = new HashSet<VideoPessoa>();
        MedidasAdaptacoesBicicletas = new HashSet<MedidasAdaptacaoBicicleta>();
        Contas = new HashSet<Conta>();
        EnderecosPessoas = new HashSet<EnderecoPessoa>();
        Fotos = new HashSet<Foto>();
        Treinadores = new HashSet<Treinador>();
        Atletas = new HashSet<Atleta>();
        DispositivosPessoas = new HashSet<DispositivoPessoa>();
    }

    private long _pessoaId;
    private string _nome, _sobrenome, _email, _sexo, _celular;
    private DateTime _dataDeNascimento;
    private double _peso;
    private double? _altura;

    public long PessoaId { get => _pessoaId; set => _pessoaId = value; }
    public string Nome { get => _nome; set => _nome = value; }
    public string Sobrenome { get => _sobrenome; set => _sobrenome = value; }
    public string Email
    {
        get => _email;
        set
        {
            _email = value;
        }
    }
    public string Sexo { get => _sexo; set => _sexo = value; }
    public DateTime DataDeNascimento { get => _dataDeNascimento; set => _dataDeNascimento = value; }
    public string Celular { get => _celular; set => _celular = value; }
    public double Peso { get => _peso; set => _peso = value; }
    public double? Altura { get => _altura; set => _altura = value; }

    [JsonIgnore]
    public virtual ICollection<VideoPessoa> VideosPessoas { get; set; }
    [JsonIgnore]
    public virtual ICollection<MedidasAdaptacaoBicicleta> MedidasAdaptacoesBicicletas { get; set; }
    [JsonIgnore]
    public virtual ICollection<Conta> Contas { get; set; }
    [JsonIgnore]
    public virtual ICollection<EnderecoPessoa> EnderecosPessoas { get; set; }
    [JsonIgnore]
    public virtual ICollection<Foto> Fotos { get; set; }
    [JsonIgnore]
    public virtual ICollection<Treinador> Treinadores { get; set; }

    public virtual ICollection<Atleta> Atletas { get; set; }
    [JsonIgnore]
    public virtual ICollection<DispositivoPessoa> DispositivosPessoas { get; set; }


}

And athlete this way:

public class Atleta
{
    public Atleta()
    {
        TiposAtletasAtletas = new HashSet<TipoAtletaAtleta>();
        TreinadoresAtletas = new HashSet<TreinadorAtleta>();
        AgendasTreinos = new HashSet<AgendaTreino>();
        TreinosAtletas = new HashSet<TreinoAtleta>();
    }
    [Key]
    public long AtletaId { get; set; }
    public virtual long AtletaIdPessoa { get; set; }

    [Required]
    [ForeignKey("AtletaIdPessoa")]
    public virtual Pessoa Pessoa { get; set; }

    public virtual ICollection<TipoAtletaAtleta> TiposAtletasAtletas { get; set; }
    public virtual ICollection<TreinadorAtleta> TreinadoresAtletas { get; set; }
    [JsonIgnore]
    public virtual ICollection<AgendaTreino> AgendasTreinos { get; set; }
    [JsonIgnore]
    public virtual ICollection<TreinoAtleta> TreinosAtletas { get; set; }
}
  • 1

    take it off: [ForeignKey("AtletaIdPessoa")] and this: public virtual long AtletaIdPessoa { get; set; } in EF Core, you do not need the property being the primary key of another object

  • The error continues

1 answer

1


Good afternoon!

I imagine Pessoa and Atleta are in the 1:1 relationship and Code First.

Read this article: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

This site has many articles about EF. But a very important observation is that the ideal is that you use Code-First Convention, which is nothing less than standard nomenclature, mainly for relational objects, in EF the nomenclature standard makes a lot of difference.

From what I understand there are several things to be done in your code to solve the problem. And All the answers are in Code-First Convention.

Come on.

1) For the primary keys of your classes you should name them only as Id

Person ->

public long Id {get;set;}

Athlete ->

public long Id {get;set;}
  • does not need the date attribute [Key]

  • I suggest you use Guid for your keys

In athlete the property person who is so:

[Required]
[ForeignKey("AtletaIdPessoa")]
public virtual Pessoa Pessoa { get; set; }

Would look like this:

public long PessoaId { get; set; }
public virtual Pessoa Pessoa { get; set; }

Because of the convention, the EF will solve the keys for you.

I hope now I can help you better, if you need more details just talk.

  • Rodrigo, nice intention to help, but it would be nice an example of how to solve the problem besides the link, and that is already a link related to the EF version.

  • Okay, so I need to confirm these entities are really in the 1:1 relationship ?

  • I hope now I have responded to contentment, thank you!

  • I’ll do what you told me and as soon as I make the modifications I’ll tell you whether it worked out or not, thank you very much for the help.

  • blz, I’ll be waiting then.

  • That’s what you said but lacked a Foreingkey("Person") On top of the Athlete’s Id if it doesn’t work.

  • Taking advantage of Rodrigo the Entity Framework has Foreing Key limitation ?

  • The Foreing Key was a forgetfulness of mine, I will improve the answer. I did not understand what you meant by limitation.

  • Limitation thus, the Entity Framework core does not allow a class to have more than 3 foreign keys per entity or a class cannot be linked to more than three entities

  • I’ve never had a problem with that, I have entities with more than 8 relationships

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.