Example #1
0
        /// <summary>
        /// 将对象转换为一条数据库记录并存入
        /// </summary>
        /// <param name="model">要存入的对象</param>
        /// <returns></returns>
        public virtual bool Add(ModelBase model)
        {
            OpenConnection();
            Type t     = model.GetType();
            var  props = t.GetProperties();
            List <PropertyInfo> baseProps  = new List <PropertyInfo>();
            PropertyInfo        primaryKey = null;
            int primaryKeyCnt = 0;

            foreach (var p in props)
            {
                if (p.PropertyType.Namespace == "System")
                {
                    baseProps.Add(p);
                }
            }

            KeyValuePair <string, object>[] vals = new KeyValuePair <string, object> [baseProps.Count];
            string[] propNms = new string[baseProps.Count];
            int      i       = 0;

            foreach (var p in baseProps)
            {
                string key   = p.Name;
                object value = null;
                if (p.IsDefined(typeof(MyPrimaryKeyAttribute)))
                {
                    primaryKeyCnt++;
                }
                if (p.IsDefined(typeof(MyAutoIncrementAttribute)) && Convert.ToInt32(p.GetValue(model)) == 0)
                {
                    continue;
                }
                value      = p.GetValue(model);
                vals[i]    = new KeyValuePair <string, object>(key, value);
                propNms[i] = key;
                i++;
            }
            string sql = stringBuilder.InsertString(GetTableName(t), propNms);
            int    res = helper.DoUpdate(sql, vals);

            // UpdateModel
            if (1 == primaryKeyCnt && 0 < res)
            {
                primaryKey = FindAutoIncrementPrimaryKey(t);
                if (null != primaryKey)
                {
                    sql = stringBuilder.SelectLastInsertRow(GetTableName(t), primaryKey.Name);
                    var table = helper.DoSelect(sql);
                    initModel(table.Rows[0], t, model);
                }
            }

            helper.ShutDown();
            return(res > 0);
        }