Error Entity Framework Core

2

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 look 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 is like this:

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; }
}
    
asked by anonymous 08.03.2018 / 17:16

1 answer

2

Good afternoon!

I imagine that Person and Athlete are in the 1: 1 relationship and Code First.

Read this article: link

This site has many articles about EF. But a very important observation is that you should use Code-First Convention, which is nothing more than a standard nomenclature, especially for Relational Objects. In EF the naming pattern makes a lot of difference.

So I realize there are several things to do in your code to solve the problem. E All answers are in Code-First Convention.

Come on.

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

Person - >

public long Id {get;set;}

Athlete - >

public long Id {get;set;}
  • do not need data annotation attribute [Key]

  • I suggest you use Guid for your keys

In athlete the property person who looks like this:

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

It would look like this:

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

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

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

    
08.03.2018 / 21:17