Exemplo n.º 1
0
        private string BuildInsertSql <T>(T entity)
        {
            PropertyInfo[] ps      = entity.GetType().GetProperties();
            List <string>  @colms  = new List <string>();
            List <string>  @params = new List <string>();

            string tableName  = GetTableName(entity);
            bool   isIdentity = false;

            foreach (PropertyInfo p in ps)
            {
                if (p.GetCustomAttributes(false).Count(o => o.GetType() == typeof(IgnoreAttribute)) > 0)
                {
                    continue;
                }

                KeyAttribute property = (KeyAttribute)p.GetCustomAttributes(false).FirstOrDefault(o => o.GetType() == typeof(KeyAttribute));
                if (property != null || !property.Identity)
                {
                    isIdentity = true;
                }

                switch (Type.GetTypeCode(p.PropertyType))
                {
                case TypeCode.DateTime:
                    if (Convert.ToDateTime(p.GetValue(entity, null)) > DateTime.MinValue)
                    {
                        @colms.Add(string.Format("{0}", p.Name));
                        @params.Add(string.Format("@{0}", p.Name));
                    }
                    ;
                    break;

                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Double:
                case TypeCode.Decimal:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    if (!p.GetValue(entity, null).ToString().Equals("0"))
                    {
                        @colms.Add(string.Format("{0}", p.Name));
                        @params.Add(string.Format("@{0}", p.Name));
                    }
                    break;

                default:
                    if ((property == null && p.GetValue(entity, null) != null) || (property != null && !property.Identity))
                    {
                        @colms.Add(string.Format("{0}", p.Name));
                        @params.Add(string.Format("@{0}", p.Name));
                    }
                    break;
                }
            }
            string sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, string.Join(", ", @colms), string.Join(", ", @params));

            if (isIdentity)
            {
                switch (DbType)
                {
                case DbType.MsSql:
                    sql += " SELECT CAST(SCOPE_IDENTITY() as int)";
                    break;

                case DbType.MySql:
                    sql += ";select last_insert_id()";
                    break;
                }
            }

            return(sql);
        }