Ejemplo n.º 1
0
        /// <summary>
        /// 通过主键和指定类型从数据库获取对象
        /// </summary>
        /// <typeparam name="T">指定类型</typeparam>
        /// <param name="keyValue">主键值(通常为Guid),不能为空</param>
        /// <returns>从数据库中得到的对象,如果数据库中没找到对象会返回一个空对象</returns>
        /// 前置条件
        /// 1.keyValue不能为空
        /// 2.传入的对象T只能有一个主键
        public T GetByKey <T>(object keyValue)
            where T : new()
        {
            PreconditionAssert.IsNotNull(keyValue, ErrorMessages.NullReferenceException);
            ORMHelper.EntityIsMappingDatabase(typeof(T), ErrorMessages.EntityMappingError);

            SelectCommandCreator dbCommandCreator = new SelectCommandCreator(_dbAccess);

            dbCommandCreator.ObjectType = typeof(T);
            dbCommandCreator.KeyValue   = keyValue;
            dbCommandCreator.SelectType = SelectType.GetOneByKeyValue;
            DbCommand dbCommand = dbCommandCreator.GetDbCommand();
            DataTable dt        = _dbAccess.GetDataTableByCommand(dbCommand);

            if (dt.Rows.Count == 0)
            {
                return(default(T));
            }
            else if (dt.Rows.Count == 1)
            {
                return(ORMHelper.ConvertDataRowToEntity <T>(dt.Rows[0]));
            }
            else
            {
                //引发数据获取结果错误
                throw new ORMException(ErrorMessages.ResultNotUniqueMessage);
            }
        }