Search code examples
c#entity-frameworkef-code-firstentity-framework-migrations

Can't make a composed primary key on EF Code First


I'm trying to make the first migration of a new project on EF, but I keep getting an exception that doesn't make sense.

I'm using separated configuration classes for each of my business classes and the one that receives the exception is this one:

public class AlunoAcessaArquivoMapeamento : EntityTypeConfiguration<AlunoAcessaArquivo> {
    public AlunoAcessaArquivoMapeamento() {
        ToTable(Regex.Replace(typeof(AlunoAcessaArquivo).Name, "([^A-Z])([A-Z])", "$1_$2").ToLower());
        HasKey(e => new {e.AlunoId, e.ArquivoId});
        HasRequired(a => a.Aluno).WithMany(a => a.AlunosAcessaArquivos).HasForeignKey(a => a.AlunoId);
        HasRequired(a => a.Arquivo).WithMany(a => a.AlunosAcessaArquivos).HasForeignKey(a => a.ArquivoId);
    }
}

The class which it configures is this one, which is a simple many-to-many relation table:

public class AlunoAcessaArquivo : EntidadeBase {

    public virtual Aluno Aluno { get; set; }

    public virtual Arquivo Arquivo { get; set; }

    public long AlunoId;
    public long ArquivoId;
}

When I try to Add-Migration I get the exception:

System.InvalidOperationException: The properties expression 'e => new <>f__AnonymousType0`2(AlunoId = e.AlunoId, ArquivoId = e.ArquivoId)' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

This exception doesn't make any sense. Notice that I configure my primary key on the forth line of the first code sample and it clearly follows the anonymous type format specified on the exception, so I'm stuck with this.


Solution

  • Your AlunoId and ArquivoId in AlunoAcessaArquivo are fields, not properties. That's the problem. Make them properties as follows:

    public class AlunoAcessaArquivo : EntidadeBase {
    
        public virtual Aluno Aluno { get; set; }
    
        public virtual Arquivo Arquivo { get; set; }
    
        public long AlunoId { get; set; } // <-- You missed { get; set; }
        public long ArquivoId { get; set; } // <-- You missed { get; set; }
    }