/// <summary>
        ///  修改,建议每次修改前先select,并放置在一个事务中。
        ///  版本控制,如果item中Version未赋值,会无法更改
        /// </summary>
        public DatabaseResult Update <T>(T item, TransactionContext transContext) where T : DatabaseEntity, new()
        {
            if (!item.IsValid())
            {
                return(DatabaseResult.Fail("entity check failed."));
            }

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            if (!entityDef.DatabaseWriteable)
            {
                return(DatabaseResult.NotWriteable());
            }

            WhereExpression <T> condition = Where <T>();

            long id      = item.Id;
            long version = item.Version;

            condition.Where(t => t.Id == id).And(t => t.Deleted == false);

            //版本控制
            condition.And(t => t.Version == version);

            try
            {
                IDbCommand dbCommand = _sqlBuilder.CreateUpdateCommand(condition, item, "default");

                long rows = _databaseEngine.ExecuteCommandNonQuery(transContext?.Transaction, entityDef.DatabaseName, dbCommand);

                if (rows == 1)
                {
                    item.Version++;
                    return(DatabaseResult.Succeeded());
                }
                else if (rows == 0)
                {
                    return(DatabaseResult.NotFound());
                }

                throw new Exception("Multiple Rows Affected instead of one. Something go wrong.");
            }
            catch (DbException ex)
            {
                //_logger.LogCritical(ex.Message);
                return(DatabaseResult.Fail(ex));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 增加,并且item被重新赋值
        /// </summary>
        public async Task <DatabaseResult> AddAsync <T>(T item, TransactionContext transContext) where T : DatabaseEntity, new()
        {
            if (!item.IsValid())
            {
                //TODO: 给所有使用到IsValid()方法的地方,都加上GetValidateErrorMessage输出
                return(DatabaseResult.Fail($"entity check failed.{item.GetValidateErrorMessage()}"));
            }

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            if (!entityDef.DatabaseWriteable)
            {
                return(DatabaseResult.NotWriteable());
            }

            IDataReader reader = null;

            try
            {
                IDbCommand dbCommand = _sqlBuilder.CreateAddCommand(item, "default");

                reader = await _databaseEngine.ExecuteCommandReaderAsync(transContext?.Transaction, entityDef.DatabaseName, dbCommand, true).ConfigureAwait(false);

                _modelMapper.ToObject(reader, item);

                return(DatabaseResult.Succeeded());
            }
            catch (DbException ex)
            {
                //_logger.LogCritical(ex.Message);
                return(DatabaseResult.Fail(ex));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
        /// <summary>
        /// 增加,并且item被重新赋值
        /// </summary>
        public DatabaseResult Add <T>(T item, TransactionContext transContext) where T : DatabaseEntity, new()
        {
            if (!item.IsValid())
            {
                return(DatabaseResult.Fail("entity check failed."));
            }

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            if (!entityDef.DatabaseWriteable)
            {
                return(DatabaseResult.NotWriteable());
            }

            IDataReader reader = null;

            try
            {
                IDbCommand dbCommand = _sqlBuilder.CreateAddCommand(item, "default");

                reader = _databaseEngine.ExecuteCommandReader(transContext?.Transaction, entityDef.DatabaseName, dbCommand, true);

                _modelMapper.ToObject(reader, item);

                return(DatabaseResult.Succeeded());
            }
            catch (DbException ex)
            {
                //_logger.LogCritical(ex.Message);
                return(DatabaseResult.Fail(ex));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
        /// <summary>
        /// 批量更改
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public DatabaseResult BatchUpdate <T>(IEnumerable <T> items, string lastUser, TransactionContext transContext) where T : DatabaseEntity, new()
        {
            if (transContext == null)
            {
                return(DatabaseResult.Fail(new ArgumentNullException(nameof(transContext))));
            }

            if (!CheckEntities <T>(items))
            {
                return(DatabaseResult.Fail("entities not valid."));
            }

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            if (!entityDef.DatabaseWriteable)
            {
                return(DatabaseResult.NotWriteable());
            }

            IDataReader reader = null;

            try
            {
                IDbCommand dbCommand = _sqlBuilder.CreateBatchUpdateStatement(items, lastUser);

                reader = _databaseEngine.ExecuteCommandReader(
                    transContext.Transaction,
                    entityDef.DatabaseName,
                    dbCommand,
                    true);

                int count = 0;

                while (reader.Read())
                {
                    int matched = reader.GetInt32(0);

                    if (matched != 1)
                    {
                        throw new DatabaseException("BatchUpdate wrong, not find the {" + count + "}th data item. ");
                    }

                    count++;
                }

                if (count != items.Count())
                {
                    throw new DatabaseException("BatchUpdate wrong number return. Some Rows not exists.");
                }

                return(DatabaseResult.Succeeded());
            }
            catch (Exception ex)
            {
                //_logger.LogCritical(ex.Message);
                return(DatabaseResult.Fail(ex));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
        /// <summary>
        /// 批量添加,返回新产生的ID列表
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public DatabaseResult BatchAdd <T>(IEnumerable <T> items, string lastUser, TransactionContext transContext) where T : DatabaseEntity, new()
        {
            if (transContext == null)
            {
                return(DatabaseResult.Fail(new ArgumentNullException(nameof(transContext))));
            }

            if (!CheckEntities <T>(items))
            {
                return(DatabaseResult.Fail("entities not valid."));
            }

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            if (!entityDef.DatabaseWriteable)
            {
                return(DatabaseResult.NotWriteable());
            }

            IDataReader reader = null;

            try
            {
                DatabaseResult result = DatabaseResult.Succeeded();

                IDbCommand dbCommand = _sqlBuilder.CreateBatchAddStatement(items, lastUser);

                reader = _databaseEngine.ExecuteCommandReader(
                    transContext.Transaction,
                    entityDef.DatabaseName,
                    dbCommand,
                    true);

                while (reader.Read())
                {
                    int newId = reader.GetInt32(0);

                    if (newId <= 0)
                    {
                        throw new DatabaseException("BatchAdd wrong new id return.");
                    }

                    result.AddId(newId);
                }

                if (result.Ids.Count != items.Count())
                {
                    throw new DatabaseException("BatchAdd wrong new id number return.");
                }

                return(result);
            }
            catch (Exception ex)
            {
                //_logger.LogCritical(ex.Message);
                return(DatabaseResult.Fail(ex));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <DatabaseResult> BatchDeleteAsync <T>(IEnumerable <T> items, string lastUser, TransactionContext transContext) where T : DatabaseEntity, new()
        {
            if (transContext == null)
            {
                return(DatabaseResult.Fail(new ArgumentNullException(nameof(transContext))));
            }

            if (!CheckEntities <T>(items))
            {
                return(DatabaseResult.Fail("Entities not valid"));
            }

            DatabaseEntityDef entityDef = _entityDefFactory.GetDef <T>();

            if (!entityDef.DatabaseWriteable)
            {
                return(DatabaseResult.NotWriteable());
            }

            IDataReader reader = null;

            try
            {
                IDbCommand dbCommand = _sqlBuilder.CreateBatchDeleteStatement(items, lastUser);
                reader = await _databaseEngine.ExecuteCommandReaderAsync(
                    transContext.Transaction,
                    entityDef.DatabaseName,
                    dbCommand,
                    true);

                int count = 0;

                while (reader.Read())
                {
                    int affected = reader.GetInt32(0);

                    if (affected != 1)
                    {
                        throw new DatabaseException("BatchDelete wrong, not found the {" + count + "}th data item. ");
                    }

                    count++;
                }

                if (count != items.Count())
                {
                    throw new DatabaseException("BatchDelete wrong number return. Some data is not found.");
                }

                return(DatabaseResult.Succeeded());
            }
            catch (Exception ex)
            {
                //_logger.Error_BatchDelete_Thrown(ex, lastUser);
                return(DatabaseResult.Fail(ex));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }