簡體   English   中英

無法在 EF Code First 上創建組合主鍵

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

我正在嘗試對 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 }'。

這個例外沒有任何意義。 請注意,我在第一個代碼示例的第四行配置了我的主鍵,它清楚地遵循異常中指定的匿名類型格式,所以我一直堅持這個。

您在AlunoAcessaArquivo中的AlunoIdArquivoId是字段,而不是屬性。 那就是問題所在。 使它們的屬性如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM