Skip to content

Instantly share code, notes, and snippets.

@mhinze
Created October 26, 2011 04:21
Show Gist options
  • Save mhinze/1315423 to your computer and use it in GitHub Desktop.
Save mhinze/1315423 to your computer and use it in GitHub Desktop.
Ef base entity
public abstract class Entity
{
protected Entity()
{
Created = SystemTime.InternalNow();
Updated = SystemTime.InternalNow();
}
[Key]
public long Id { get; set; }
[HiddenInput(DisplayValue = false)]
public DateTime Created { get; set; }
[HiddenInput(DisplayValue = false)]
public DateTime Updated { get; set; }
public override bool Equals(object obj)
{
var other = obj as Entity;
if (other == null)
return false;
if (ReferenceEquals(this, other))
return true;
bool typesMatch = GetUnproxiedType().Equals(other.GetUnproxiedType());
bool idsMatch = PersistentAndSame(other);
return typesMatch && idsMatch;
}
public override int GetHashCode()
{
// ReSharper disable BaseObjectGetHashCodeCallInGetHashCode
// http://msdn.microsoft.com/en-us/library/system.object.gethashcode(v=VS.110).aspx
if (IsTransient()) return base.GetHashCode();
// ReSharper restore BaseObjectGetHashCodeCallInGetHashCode
unchecked
{
return (GetUnproxiedType().GetHashCode()*31) ^ Id.GetHashCode();
}
}
public static bool operator ==(Entity left, Entity right)
{
return Equals(left, right);
}
public static bool operator !=(Entity left, Entity right)
{
return !Equals(left, right);
}
bool PersistentAndSame(Entity compareTo)
{
return (!Id.Equals(default(long))) &&
(!compareTo.Id.Equals(default(long))) && Id.Equals(compareTo.Id);
}
bool IsTransient()
{
return Id == default(long);
}
public Type GetUnproxiedType()
{
return ObjectContext.GetObjectType(GetType());
}
public override string ToString()
{
return string.Format("{0} [{1}]", GetUnproxiedType().Name, Id);
}
}
@mhinze
Copy link
Author

mhinze commented Oct 26, 2011

might want to implement stronger gethashcode.. that's sorta funky.. the hash code should be deterministic across states throughout the object lifetime - this dude will mess up your hashtable if you persist him while he's in there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment