public string GetSQLUpdateStatement <T>(T t, Attribute lookupAttribute) { StringBuilder sb = new StringBuilder(); List <string> setValues = new List <string>(); List <string> whereValues = new List <string>(); string tableName = t.GetType().ToString(); sb.AppendLine($"Update {t.GetType().Name} SET "); int count = t.GetType().GetProperties().Count(); for (int i = 0; i < count; i++) { string fieldName = t.GetType().GetProperties()[i].Name; PropertyDescriptor prop = TypeDescriptor.GetProperties(t)[fieldName]; if (prop.Attributes.Contains(lookupAttribute)) { setValues.Add($" {fieldName} = @{fieldName} "); } } if (setValues.Count == 0) { throw new Exception("Nothing to update in SQL"); } sb.AppendLine(string.Join(",", setValues)); sb.AppendLine("Where "); Dapper.Contrib.Extensions.ExplicitKeyAttribute attKey = new Dapper.Contrib.Extensions.ExplicitKeyAttribute(); Dapper.Contrib.Extensions.KeyAttribute attKeyNormal = new Dapper.Contrib.Extensions.KeyAttribute(); for (int i = 0; i < count; i++) { string fieldName = t.GetType().GetProperties()[i].Name; PropertyDescriptor prop = TypeDescriptor.GetProperties(t)[fieldName]; if (prop.Attributes.Contains(attKey)) { whereValues.Add($"{fieldName} = @{fieldName} "); } else if (prop.Attributes.Contains(attKeyNormal)) { whereValues.Add($"{fieldName} = @{fieldName} "); } } sb.AppendLine(string.Join(" AND ", whereValues)); if (whereValues.Count == 0) { throw new Exception("No key is define in Model"); } return(sb.ToString()); }
public bool HasIdentityFieldInTable <T>() { Dapper.Contrib.Extensions.KeyAttribute attKeyNormal = new Dapper.Contrib.Extensions.KeyAttribute(); int count = typeof(T).GetProperties().Count(); for (int i = 0; i < count; i++) { string fieldName = typeof(T).GetProperties()[i].Name; PropertyDescriptor prop = TypeDescriptor.GetProperties(typeof(T))[fieldName]; if (prop.Attributes.Contains(attKeyNormal)) { return(true); } } return(false); }