我首先使用带有 EntityFramework 代码的 ASP.NET MVC。
我正在尝试为将保存到我的数据库中的所有对象创建一个基类(这里称为实体类)。
有没有在基类中实现IEquatable的好方法?在我的实现中,我检查了类型和 ID——这是一个好方法吗?这会始终返回最终的派生类型吗?中间 parent 呢?
对象
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)
{
}
}
数据库
每个派生对象类型通常都存在于单独的数据库中。但是,会有一些对象具有共享主键的中间继承父对象。
假设有三个表,其中包含以下列: 实体
- 内容
- 身份证
- 姓名
- 页面
- 身份证
- 正文
- 用户
- 身份证
- 姓名
因此,Page 和 Content 表共享一个主键。
最佳答案
- 无需实现 IEquitable,它不提供任何值(value)(既没有性能值(value),也没有可读性值(value))。
- 在您的比较中,您仅依靠引用相等性检查。您还应该检查 ID 是否相等。
- 您的 GetHashCode() 实现不是最优的,您还应该包括实体的类型。
- 您确定所有实体都将具有 Name 属性吗?在基类中,您应该包含存在于限界上下文的每个实体中的属性。
我在这里详细描述这个主题:Domain object base class .
关于c# - 在基类中实现 IEquatable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596742/