using System.Collections.Concurrent; using System.Data; namespace ManagementApp.Dapper.AExtentions { public class TableMapper { private static readonly ConcurrentDictionary TableNames = new(); private static string _prefix = string.Empty; /// /// Used to setup custom table conventions. /// /// table name prefix /// table name suffix // ReSharper disable once UnusedMember.Global public static void SetupConvention(string tablePrefix) { if (!TableNames.IsEmpty) { throw new InvalidConstraintException("TableMapper.SetupConvention called after usage."); } _prefix = tablePrefix; TableNames.Clear(); } internal static string GetTableName(Type type) { if (TableNames.TryGetValue(type.TypeHandle, out var name)) { return name; } var tableAttr = type.GetCustomAttributes(false).SingleOrDefault(attr => attr.GetType().Name == "TableAttribute") as dynamic; if (tableAttr != null) { name = tableAttr.Name; if (tableAttr.Schema != null) { name = tableAttr.Schema + "." + tableAttr.Name; } } else { name = type.IsInterface && type.Name.StartsWith("I") ? type.Name.Substring(1) : type.Name; name = $"{_prefix}{name}"; } TableNames[type.TypeHandle] = name; return name; } } }