最初に EntityFramework コードで ASP.NET MVC を使用しています。
データベースに保存されるすべてのオブジェクトの基本クラスを作成しようとしています (ここでは Entity クラスと呼びます)。
基本クラスに IEquatable を実装する良い方法はありますか? 私の実装では、型と ID をチェックします - これは良い方法ですか? これは常に最終的な派生型を返しますか? 中間の親はどうですか?
オブジェクト
public abstract class Entity : IEquatable<Entity>
{
public int ID { get; set; }
public string Name { get; set; }
public Entity(string Name)
{
this.Name = Name;
}
public override string ToString() { return Name; }
public override int GetHashCode() { return ID.GetHashCode(); }
public override bool Equals(object obj) { return this == (Entity)obj; }
public bool Equals(Entity other) { return this == other; }
public static bool operator ==(Entity x, Entity y) { return Object.ReferenceEquals(x, y) ? true : ((object)x == null || (object)y == null) ? false : (x.GetType() == y.GetType() && x.ID.Equals(y.ID)); }
public static bool operator !=(Entity x, Entity y) { return !(x == y); }
}
public abstract class Content : Entity
{
public Content(string Name) : base(Name)
{
}
}
public class Page : Content
{
public string Body { get; set; }
public Page(string Name) : base(Name)
{
}
}
public class User : Entity
{
public User(string Name) : base(Name)
{
}
}
データベース
通常、各派生オブジェクト タイプは個別のデータベースに存在します。ただし、主キーを共有する中間の継承された親を持つオブジェクトがいくつかあります。
次の列を持つ 3 つのテーブルがあるとします。
- コンテンツ
- ID
- 名前
- ページ
- ID
- 体
- ユーザー
- ID
- 名前
したがって、Page テーブルと Content テーブルは主キーを共有します。