Ejemplo n.º 1
0
        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="primaryField"></param>
        /// <param name="fields"></param>
        public void Update(PrimaryKeyValueDictionary primaryField, params FieldValueDictionary[] fields)
        {
            StringBuilder sb = new StringBuilder(300);

            sb.Append("update " + tableName + " set ");

            IList <DbParameter> parameters = new List <DbParameter>();
            string fieldName = null;

            foreach (FieldValueDictionary f in fields)
            {
                fieldName = f.GetFieldName();
                sb.Append(fieldName + "=@" + fieldName + ",");
                parameters.Add(db.DataBaseAdapter.CreateParameter("@" + fieldName, f.Value));
            }
            sb.Remove(sb.Length - 1, 1); //删除最后的,
            fieldName = primaryField.GetFieldName();
            sb.Append(" where " + fieldName + "=@" + fieldName);
            parameters.Add(db.DataBaseAdapter.CreateParameter("@" + fieldName, primaryField.Value));

            db.ExecuteNonQuery(sb.ToString(), parameters.ToArray());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 根据主键获取单个实体
        /// </summary>
        /// <param name="primaryField"></param>
        /// <returns></returns>
        public Entity Get(PrimaryKeyValueDictionary primaryField)
        {
            string fieldName = primaryField.GetFieldName();
            string sql       = "SELECT TOP 1 * FROM " + tableName +
                               " WHERE " + fieldName + "=@" + fieldName;

            Entity          obj = null;
            ColumnAttribute attr;
            Type            type = typeof(Entity);
            Assembly        ass  = type.Assembly;


            db.ExecuteReader(new SqlQuery(sql, new object[, ]
            {
                { "@" + fieldName, primaryField.Value }
            }), rd =>
            {
                object[] attrs; //columnAttributes
                while (rd.Read())
                {
                    obj = ass.CreateInstance(type.ToString(), true) as Entity;
                    foreach (PropertyInfo p in properties)
                    {
                        attrs = p.GetCustomAttributes(typeof(ColumnAttribute), true);
                        if (attrs.Length == 0)
                        {
                            continue;
                        }
                        attr = attrs[0] as ColumnAttribute;
                        p.SetValue(obj, Convert.ChangeType(rd[attr.Name ?? p.Name],
                                                           p.PropertyType), null);
                    }
                    break;
                }
            });

            return(obj);
        }