我首先使用带有 EntityFramework 代码的 ASP.NET MVC。
我正在尝试为将保存到我的数据库中的所有对象(这里称为实体类)创建一个基类。
有没有在基类中实现 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)
{
}
}
数据库
每个派生对象类型通常存在于单独的数据库中。但是,会有一些具有中间继承父级的对象共享主键。
假设有三个具有以下列的表: 实体
- 内容
- ID
- 姓名
- 页
- ID
- 身体
- 用户
- ID
- 姓名
因此,Page 和 Content 表共享一个主键。