I am using ASP.NET MVC with EntityFramework code first.
I am attempting to create a base class for all objects that will be saved to my database (here called the Entity class).
Is there a good way of implementing IEquatable in the base class? In my implementation, I check the type and ID - is this a good way of doing it? Will this always return the ultimate derived type? What about intermediate parents?
Objects
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)
{
}
}
Database
Each derived object type will normally exist in a separate database. However, there will be some objects with intermediate inherited parents which share primary keys.
Let's say that there are three tables with the following columns: Entity
- Content
- ID
- Name
- Page
- ID
- Body
- User
- ID
- Name
Therefore, the Page and Content tables share a Primary Key.