Esempio n. 1
0
        protected override DbCommand BuildDeleteCommand(SqlDeleteCommand deleteCommand)
        {
            NpgsqlCommand     cmd = new NpgsqlCommand();
            BuildQueryContext ctx = new BuildQueryContext(cmd, deleteCommand);

            //设置上下文
            ctx.BeginBuildQuery(deleteCommand);

            EntityModel m = Runtime.RuntimeContext.Current.GetModelAsync <EntityModel>(deleteCommand.T.ModelID).Result;

            ctx.AppendFormat("Delete From \"{0}\" t ", m.GetSqlTableName(false, null));

            //构建Where
            ctx.CurrentQueryInfo.BuildStep = BuildQueryStep.BuildWhere;
            if (!Expression.IsNull(deleteCommand.Filter))
            {
                ctx.Append(" Where ");
                BuildExpression(ctx.CurrentQuery.Filter, ctx);
            }

            //构建Join
            ctx.CurrentQueryInfo.BuildStep = BuildQueryStep.BuildJoin;
            var q1 = (SqlQueryBase)ctx.CurrentQuery;

            if (q1.HasJoins) //先处理每个手工的联接及每个手工联接相应的自动联接
            {
                BuildJoins(q1.Joins, ctx);
            }
            ctx.BuildQueryAutoJoins(q1); //再处理自动联接

            ctx.EndBuildQuery(deleteCommand);
            return(cmd);
        }
Esempio n. 2
0
        public async Task <int> ExecCommandAsync(SqlDeleteCommand deleteCommand, DbTransaction txn = null)
        {
            //暂不支持无条件删除,以防止误操作
            if (Expressions.Expression.IsNull(deleteCommand.Filter))
            {
                throw new NotSupportedException("Delete must assign Where condition");
            }

            var cmd = BuildDeleteCommand(deleteCommand);

            cmd.Connection  = txn != null ? txn.Connection : MakeConnection();
            cmd.Transaction = txn;
            if (txn == null)
            {
                await cmd.Connection.OpenAsync();
            }
            Log.Debug(cmd.CommandText);
            //执行命令
            try
            {
                return(await cmd.ExecuteNonQueryAsync());
            }
            catch (Exception ex)
            {
                Log.Warn($"Exec sql error: {ex.Message}\n{cmd.CommandText}");
                throw;
            }
            finally
            {
                if (txn == null)
                {
                    cmd.Connection.Dispose();
                }
            }
        }