无法在EF Code First上创建组合主键

时间:2019-04-08 12:21:25

标签: c# entity-framework ef-code-first ef-migrations

我正在尝试在EF上进行新项目的第一次迁移,但是我不断收到没有道理的异常。

我正在为每个业务类使用单独的配置类,而接收到异常的是这个类:

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);
    }
}

它配置的类就是这个类,它是一个简单的多对多关系表:

public class AlunoAcessaArquivo : EntidadeBase {

    public virtual Aluno Aluno { get; set; }

    public virtual Arquivo Arquivo { get; set; }

    public long AlunoId;
    public long ArquivoId;
}

当我尝试Add-Migration时出现异常:

  

System.InvalidOperationException:属性表达式'e => new <> f__AnonymousType0`2(AlunoId = e.AlunoId,ArquivoId = e.ArquivoId)'无效。该表达式应表示一个属性:C#:'t => t.MyProperty'VB.Net:'Function(t)t.MyProperty'。指定多个属性时,请使用匿名类型:C#:'t => new {t.MyProperty1,t.MyProperty2}'VB.Net:'Function(t)New with {t.MyProperty1,t.MyProperty2}'。

此异常没有任何意义。请注意,我在第一个代码示例的第四行配置了主键,并且它显然遵循了异常中指定的匿名类型格式,因此我对此感到困惑。

观察:我知道我的代码包含葡萄牙语文本,可以将其翻译成英文,但前提是严格必要。

1 个答案:

答案 0 :(得分:2)

您在AlunoId中的ArquivoIdAlunoAcessaArquivo是字段,而不是属性。那就是问题所在。使它们具有以下属性:

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; }
}