BaseEntity.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace GreenTree.Nachtragsmanagement.Core
  7. {
  8. public abstract class BaseEntity
  9. {
  10. /// <summary>
  11. /// Gets or sets the entity identifier
  12. /// </summary>
  13. public int Id { get; set; }
  14. public override bool Equals(object obj)
  15. {
  16. return Equals(obj as BaseEntity);
  17. }
  18. private static bool IsTransient(BaseEntity obj)
  19. {
  20. return obj != null && Equals(obj.Id, default(int));
  21. }
  22. private Type GetUnproxiedType()
  23. {
  24. return GetType();
  25. }
  26. public virtual bool Equals(BaseEntity other)
  27. {
  28. if (other == null)
  29. return false;
  30. if (ReferenceEquals(this, other))
  31. return true;
  32. if (!IsTransient(this) &&
  33. !IsTransient(other) &&
  34. Equals(Id, other.Id))
  35. {
  36. var otherType = other.GetUnproxiedType();
  37. var thisType = GetUnproxiedType();
  38. return thisType.IsAssignableFrom(otherType) ||
  39. otherType.IsAssignableFrom(thisType);
  40. }
  41. return false;
  42. }
  43. public override int GetHashCode()
  44. {
  45. if (Equals(Id, default(int)))
  46. return base.GetHashCode();
  47. return Id.GetHashCode();
  48. }
  49. public static bool operator ==(BaseEntity x, BaseEntity y)
  50. {
  51. return Equals(x, y);
  52. }
  53. public static bool operator !=(BaseEntity x, BaseEntity y)
  54. {
  55. return !(x == y);
  56. }
  57. }
  58. }