/// <summary> /// 通过对象已有的主键值(可以多个主键)和指定类型从数据库获取对象 /// </summary> /// <typeparam name="T">指定类型</typeparam> /// <param name="entity">外部构造的对象,不能为空</param> /// <returns>从数据库中得到的对象,如果数据库中没找到对象会返回一个空对象</returns> /// 前置条件 /// 传入的entity对象不能为空 public T GetByKeys <T>(T entity) where T : new() { PreconditionAssert.IsNotNull(entity, ErrorMessages.NullReferenceException); ORMHelper.EntityIsMappingDatabase(entity.GetType(), ErrorMessages.EntityMappingError); ORMHelper.CheckEntityKey(entity); SelectCommandCreator dbCommandCreator = new SelectCommandCreator(_dbAccess); dbCommandCreator.Entity = entity; dbCommandCreator.SelectType = SelectType.GetOneByEntityKey; 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); } }
/// <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); } }