EntityHelper.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Reflection;
  3. using Abp.MultiTenancy;
  4. using Abp.Reflection;
  5. namespace Abp.Domain.Entities
  6. {
  7. /// <summary>
  8. /// Some helper methods for entities.
  9. /// </summary>
  10. public static class EntityHelper
  11. {
  12. public static bool IsEntity(Type type)
  13. {
  14. return ReflectionHelper.IsAssignableToGenericType(type, typeof(IEntity<>));
  15. }
  16. public static Type GetPrimaryKeyType<TEntity>()
  17. {
  18. return GetPrimaryKeyType(typeof(TEntity));
  19. }
  20. /// <summary>
  21. /// Gets primary key type of given entity type
  22. /// </summary>
  23. public static Type GetPrimaryKeyType(Type entityType)
  24. {
  25. foreach (var interfaceType in entityType.GetTypeInfo().GetInterfaces())
  26. {
  27. if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEntity<>))
  28. {
  29. return interfaceType.GenericTypeArguments[0];
  30. }
  31. }
  32. throw new AbpException("Can not find primary key type of given entity type: " + entityType + ". Be sure that this entity type implements IEntity<TPrimaryKey> interface");
  33. }
  34. public static object GetEntityId(object entity)
  35. {
  36. if (!ReflectionHelper.IsAssignableToGenericType(entity.GetType(), typeof(IEntity<>)))
  37. {
  38. throw new AbpException(entity.GetType() + " is not an Entity !");
  39. }
  40. return ReflectionHelper.GetValueByPath(entity, entity.GetType(), "Id");
  41. }
  42. public static string GetHardDeleteKey(object entity, int? tenantId)
  43. {
  44. if (MultiTenancyHelper.IsMultiTenantEntity(entity))
  45. {
  46. var tenantIdString = tenantId.HasValue ? tenantId.ToString() : "null";
  47. return entity.GetType().FullName + ";TenantId=" + tenantIdString + ";Id=" + GetEntityId(entity);
  48. }
  49. return entity.GetType().FullName + ";Id=" + GetEntityId(entity);
  50. }
  51. }
  52. }