예제 #1
0
파일: EntityManager.cs 프로젝트: lyfb/cms-1
        /// <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.GetDialect().CreateParameter("@" + fieldName, f.Value));
            }
            sb.Remove(sb.Length - 1, 1); //删除最后的,
            fieldName = primaryField.GetFieldName();
            sb.Append(" where " + fieldName + "=@" + fieldName);
            parameters.Add(db.GetDialect().CreateParameter("@" + fieldName, primaryField.Value));

            db.ExecuteNonQuery(sb.ToString(), parameters.ToArray());
        }
예제 #2
0
파일: EntityManager.cs 프로젝트: lyfb/cms-1
        /// <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);
        }