internal static void Add <T>(T entity) { StringBuilder sqlsb = new StringBuilder(); List <string> PropertyNames = new List <string>(); List <SqlParameter> psList = new List <SqlParameter>(); //拼接属性名 foreach (var item in typeof(T).GetProperties()) { IdentityAttribute identity = Attribute.GetCustomAttribute(item, typeof(IdentityAttribute)) as IdentityAttribute; if (identity == null) { psList.Add(new SqlParameter(item.Name, item.GetValue(entity, null))); PropertyNames.Add(item.Name); } } //拼接属性值 //string sql = "insert into producte(a,b,c) values(a,b,c)"; sqlsb.Append("insert into " + GetTableName(typeof(T)) + "("); sqlsb.Append(string.Join(",", PropertyNames.ToArray())); sqlsb.Append(") values("); sqlsb.Append("@"); sqlsb.Append(string.Join(",@", PropertyNames.ToArray())); sqlsb.Append(");select @@identity"); try { SqlHelper.ExecuteScalar(sqlsb.ToString(), psList.ToArray()); } catch (Exception ex) { } }
internal static string GetIdentityName(Type type) { foreach (var item in type.GetProperties()) { IdentityAttribute identity = Attribute.GetCustomAttribute(item, typeof(IdentityAttribute)) as IdentityAttribute; if (identity != null && identity.IsIdentity) { return(item.Name); } } return(""); }