0

私はefコードの最初のアプローチで実験しています。私は基本クラスを持っています:

    [Serializable]
    [Table("PayerEntity")]
    public abstract class PayerEntity
    {
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int PayerEntityId { get; set; }
    }

別のものはそれからの子孫です:

    [Serializable]
    [Table("Group")]
    public class Group : PayerEntity
    {
      public int GroupId { get; set; }

      [MaxLength(50,ErrorMessage = "Max 50")]
      public string SomeGroupProp { get; set; }
    }

コンテキスト クラスで、OnModelCreating メソッドをオーバーライドします。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      modelBuilder.Entity<Group>().HasKey(p => new { p.PayerEntityId, p.GroupId });
      base.OnModelCreating(modelBuilder);
    }

ただし、「PayerEntityId」列のみが主キーになります。どんな助けでも本当に感謝しています。

ありがとう、ピーター

4

1 に答える 1

1

キー設定が異なるテーブル間に1対1の関係を作成したいようです。これは(少なくともSQLでは)制約することができないため、EFは、両方のテーブルに同じキーを使用させることにより、1対1の関係を定義するのが最善であるように思われます。

1対多の関係が必要な場合は、相互に継承しないクラスを作成する必要がPayerEntityあります。Group

[Table("PayerEntity")]
public  class PayerEntity
{
  public PayerEntity()
  {
        this.Groups = new HashSet<Group>();
  }

  [Key]
  public int PayerEntityId { get; set; }
  public virtual ICollection<Group> Groups { get; set; }
}

[Table("Group")]
public class Group
{
  public int PayerEntityId { get; set; }
  public int GroupId { get; set; }
  public virtual PayerEntity PayerEntity { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Group>().HasKey(p => new { p.PayerEntityId, p.GroupId });
  base.OnModelCreating(modelBuilder);

  modelBuilder.Entity<Group>()
        .HasRequired(a => a.PayerEntity)
        .WithMany(b => b.Groups)
}
于 2013-01-26T17:20:52.827 に答える