1

次の設定で関連付けプロパティを作成したいと思います。

public class ClassType1{
    [Key]
    public int type1_ID { get;set; }
    public int type2_ID { get;set; }  // In database, this is a foreign key linked to ClassType2.type2_ID
    public ClassType2 type2Prop { get;set; }
}

public class ClassType2{
    [Key]
    public int type2_ID { get;set; }
}

私の問題は、type2Prop が外部キーを見つけられないことです。本当に「type2_ID」を探すべきなのに、存在しない「type2Prop_ID」を探そうとしている。これが私が得るエラーです:

{"Invalid column name 'type2Prop_ID'."}

ClassType2 のキーとして使用するプロパティを指定するにはどうすればよいですか?

4

2 に答える 2

3

試着: ForeignKeyAttribute_type2Prop

using System.ComponentModel.DataAnnotations.Schema;

public class ClassType1
{
  [Key]
  public int type1_ID { get; set; }

  public int type2_ID { get; set; }  // In database, this is a foreign key linked to ClassType2.type2_ID

  [ForeignKey("type2_ID")]
  public virtual ClassType2 type2Prop { get; set; }
}

public class ClassType2
{
  [Key]
  public int type2_ID { get;set; }
}

また、Fluent API を使用してリファクタリング防止の方法で行うこともできます (つまり、将来プロパティの名前を変更すると、コンパイラはマッピングも変更する必要があることを通知します)。このような単純なケースでは少し醜いですが、より堅牢でもあります。DbContextクラスでは、次のようなものを追加できます。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<ClassType1>().HasRequired(x => x.type2Prop)
                                   .WithMany()
                                   .HasForeignKey(x => x.type2_ID);
}
于 2013-05-06T18:40:18.053 に答える