web-dev-qa-db-ja.com

Entity Framework DB-まず、継承を実装します

エンティティフレームワーク6.0とデータベースファーストアプローチを使用して継承を実装しようとしています。 OK、次のようなPersonエンティティとOrganizationエンティティがあるとします。

// a simplified version of organization entity
public class Organization
{
    public Guid ID { get; set; }
    public string Nickname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string OfficialName { get; set; }
    public Guid CEOID { get; set; }
    public DateTime? RegisterDate { get; set; }
}

// a simplified version of person entity
public class Person
{
    public Guid ID { get; set; }
    public string Nickname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public Guid PersonID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string NationalCode { get; set; }
    public DateTime? BirthDate { get; set; }
}

これら2つのテーブルをデータベースに作成できますが、継承を使用して、PersonOrganizationの両方で繰り返されるフィールドを次のような別の基本クラスに含めることができます。

public class Identity
{
    // These fields are the common fields between Person and Organization
    public Guid ID { get; set; }
    public string Nickname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}

Db-firstアプローチでこれをどのように達成できますか?

17
Ashkan

考えられる1つの方法は、one table for each type called [〜#〜] tpt [〜#〜](table-per-type )、私が使用することを好みます。これを実現するには、次の図に示すモデルのようにテーブルを定義します。

table hierarchy

子とベースエンティティ間の関係は、pk列でone-to-oneであり、すべての共通フィールドがベーステーブルに移動されることに注意してください。テーブルを作成したら、Visual Studioのモデルページを右クリックし、データベースからモデルを更新...を選択し、[追加]タブでこれら3つのテーブルを選択して追加します。最初に、このモデル図が表示されます。これは少し変更する必要があります。

tables added at first

PersonOrganizationに対して別々に次の手順を実行します。

  • エンティティを右クリックして、プロパティを選択します
  • 基本タイププロパティでIdentityを選択します
  • 選択してから関連付けを削除このエンティティとIdentityの間
  • 選択してからPKを削除(ID列)このエンティティ(ベースエンティティから継承)

これらの手順の後、モデルを保存します。これで、モデルは次のようになります。

the changed model

今、あなたのプロジェクトをコンパイルして、あなたの人生を楽しんでください!

追加リソース:
Entity Framework Designer TPHの継承

25
Ashkan