Error generating Migration after changing a relationship

Asked

Viewed 149 times

1

I’m having an error when changing a relationship Many to Many in the Entity framework

I had 3 classes:

Politics 1-n Politicabnormal n-1 Normative

It turns out that I didn’t want to map this auxiliary table in my hand, so I deleted the Politicabnormal class and in the Politica map I did the following:

this.HasMany(t => t.Politica)
            .WithMany(d => d.Normativo)
            .Map(d => {
                d.MapLeftKey("PoliticaID");
                d.MapRightKey("NormativoID");
                d.ToTable("PoliticaNormativo");
            });

Theoretically this change should not generate any modification, but when running now an add-Migration I have the following error:

 System.InvalidOperationException: Sequence contains no matching element
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<GetStoreAssociationTypePairs>d__70.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__22`3.MoveNext()
   at System.Linq.Enumerable.<DistinctIterator>d__63`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.FindAssociationTypePairs(ICollection`1 entityTypePairs)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains no matching element

Politics:

public class Politica
{
    [Key]
    public int PoliticaID { get; set; }

    [Display(Name = "Nome da Politica")]
    [Required(ErrorMessage = "Nome é obrigatório.")]
    [StringLength(80, ErrorMessage = "Nome deve conter no máximo 80 caracteres.")]
    public string Nome { get; set; }

    [Display(Name = "Data Registro")]
    [Required(ErrorMessage = "Data Registro é obrigatório.")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public System.DateTime DataRegistro { get; set; }

    [Display(Name = "Início Vigência")]
    public Nullable<DateTime> VigenciaInicio { get; set; }

    [Display(Name = "Fim Vigência")]
    public Nullable<DateTime> VigenciaFim { get; set; }

    [Display(Name = "Status")]
    [Required(ErrorMessage = "Status é obrigatório.")]
    public PoliticaStatus Status { get; set; }

    [Display(Name = "Revisão da Periodicidade")]
    [Range(1, 99, ErrorMessage = "Revisão da Periodicidade é obrigatória.")]
    public Nullable<int> PeriodicidadeRevisao { get; set; }

    [Display(Name = "Resumo")]
    [Required(ErrorMessage = "Resumo é obrigatório")]
    [StringLength(4000, ErrorMessage = "Campo Resumo deve conter até 4000 caracteres.")]
    public string Resumo { get; set; }

    [Display(Name = "Criador Responsável")]
    [Required(ErrorMessage = "Criador Responsável é obrigatório.")]
    public int CriadorID { get; set; }

    [Display(Name = "Responsável da Alteração")]
    [Required(ErrorMessage = "Responsável Alteração é obrigatório.")]
    public int UsuarioAlteracaoID { get; set; }

    [Display(Name = "Data de Alteração")]
    [Required(ErrorMessage = "Data de Alteração é obrigatório.")]
    public DateTime DataAlteracao { get; set; }

    [Display(Name = "Registro Excluido")]
    [Required(ErrorMessage = "Registro Excluido é obrigatório.")]
    public Boleano IsDeleted { get; set; }

    [Display(Name = "Justificativa Exclusão")]
    [StringLength(4000, ErrorMessage = "Campo Justificativa Exclusão deve conter até 4000 caracteres.")]
    public string JustificativaDeleted { get; set; }

    public virtual ICollection<Normativo> Normativo { get; set; }

}

Normative:

public class Normativo : IValidatableObject
{
    [Key]
    public int NormativoID { get; set; }

    [Display(Name = "Assunto")]
    [Required(ErrorMessage = "Assunto é obrigatório")]
    [StringLength(80, ErrorMessage = "Campo Assunto deve conter até 80 caracteres.")]
    public string Assunto { get; set; }

    [Display(Name = "Número")]
    [Required(ErrorMessage = "Número do normativo é obrigatório")]
    [StringLength(20, ErrorMessage = "Campo Número deve conter até 20 caracteres.")]
    public string Numero { get; set; }

    [Display(Name = "Tipo Documento")]
    [Required(ErrorMessage = "Tipo Documento é obrigatório.")]
    [Range(1, int.MaxValue, ErrorMessage = "Tipo Documento é obrigatório.")]
    public int TipoDocumentoID { get; set; }

    [Display(Name = "Data Publicação")]
    [Required(ErrorMessage = "Data da Publicação é obrigatório.")]
    public DateTime DataPublicacao { get; set; }

    [Display(Name = "Início Vigência")]
    [Required(ErrorMessage = "Início Vigência é obrigatório")]
    public DateTime VigenciaInicio { get; set; }

    [Display(Name = "Fim Vigência")]
    public Nullable<DateTime> VigenciaFim { get; set; }

    [Display(Name = "Resumo")]
    [Required(ErrorMessage = "Resumo é obrigatório")]
    //[StringLength(2000, ErrorMessage = "Campo Resumo deve conter até 2000 caracteres.")] Removido pelo Campo do Conteudo do BacenIntegraca ser maior
    public string Resumo { get; set; }

    [Display(Name = "Situação")]
    public Situacao Situacao { get; set; }

    [Display(Name = "Data")]
    public Nullable<DateTime> DataSituacao { get; set; }

    [Display(Name = "Justificativa")]
    [StringLength(1000, ErrorMessage = "Campo Justificativa deve conter até 1000 caracteres.")]
    public string JustificativaSituacao { get; set; }

    [Display(Name = "Usuário")]
    public Nullable<int> UsuarioSituacao { get; set; }

    public virtual ICollection<Normativo> NormativoRelacionadoMaster { get; set; }
    public virtual ICollection<Normativo> NormativoRelacionado { get; set; }

    public virtual ICollection<Normativo> NormativoRevogadoMaster { get; set; }
    public virtual ICollection<Normativo> NormativoRevogado { get; set; }

    public virtual ICollection<Solicitacao> NormativoSolicitacao { get; set; }
    public virtual ICollection<Requisito> Requisito { get; set; }

    public virtual ICollection<Politica> Politica { get; set; }
    public virtual ICollection<NormativoControle> NormativoControle { get; set; }

    public virtual TipoDocumento TipoDocumento { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (VigenciaInicio < DataPublicacao)
        {
            yield return new ValidationResult("Data de início vigência não pode ser menor que a data publicação.", new[] { "VigenciaInicio" });
        }

        if (NormativoID < 1)
        {
            Situacao = Situacao.Pendente;
        }
    }
}
  • Could post the entities Politica e Normativa?

  • You have the table in the bank and are trying to run the add-Migration ?

  • @Gabrielcoletta added the classes

  • @Marconciliosouza yes because I made other modifications too but I commented them to look for and the error was in this same modification, but also if there was nothing it was to generate the empty Migration instead of giving error

  • @Eduardosampaio can not drop the bank the system is in production

  • Your command executed normally ? I think you would have run Add-Migration Initialcreate -Ignorechanges. , and then the Update-Database

  • @Marconciliosouza I tried to run the add-Migration "name" only, what the add-Migration Initialcreate -Ignorechanges would do?

  • https://msdn.microsoft.com/en-us/library/dn579398(v=vs.113). aspx This creates an Empty Migration with the Current model as a snapshot.

  • I noticed that your left and right key mapping is reversed, note that the description of the method is: the left/right Foreign key points to the PARENT Entity of the navigation Property specified... try something like: d.MapLeftKey("NormativoID"); d.MapRightKey("PoliticaID");. Tell me if it corrects the mistake.

  • @Gabrielcoletta really was inverted, but this was not the cause of the problem. Thanks would go unnoticed

  • @Marconciliosouza I think this is really the best solution but so I have to add with -Ignorechanges only in the modifications that are giving error to then add the other, kind of laborious, you know the cause of this error?

Show 6 more comments
No answers

Browser other questions tagged

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