Просмотр исходного кода

支持多表、表数组、id数组批量更新

苏智明 2 лет назад
Родитель
Сommit
a93d245c5c

+ 13 - 29
Admin.NET/Admin.NET.Core/Service/APIJSON/APIJSONService.cs

@@ -128,14 +128,14 @@ public class APIJSONService : IDynamicApiController, ITransient
                     var id = _selectTable.InsertSingle(talbeName, cols, role);
                     ids.Add(id);
                 }
-                result = JToken.FromObject(ids);               
+                result = JToken.FromObject(new { id = ids,count=ids.Count });               
             }
             //单条插入
             else
             {
                 var cols = table.Value.ToObject<JObject>();
                 var id = _selectTable.InsertSingle(talbeName, cols, role);
-                result = JToken.FromObject(id);
+                result = JToken.FromObject(new { id });
             }
 
             ht.Add(talbeName, result);
@@ -144,42 +144,22 @@ public class APIJSONService : IDynamicApiController, ITransient
         return ht;
     }
     /// <summary>
-    /// 修改
+    /// 修改,只支持id作为条件
     /// </summary>
-    /// <param name="json"></param>
+    /// <param name="tables">支持多表、多id批量更新</param>
     /// <returns></returns>
     [HttpPost("put")]
     [UnitOfWork]
-    public JObject Edit([FromBody] JObject jobject)
+    public JObject Edit([FromBody] JObject tables)
     {
         JObject ht = new JObject();
 
-        foreach (var item in jobject)
+        foreach (var table in tables)//每个表
         {
-            string key = item.Key.Trim();
+            string tableName = table.Key.Trim();
             var role = _identityService.GetRole();
-            if (!role.Update.Table.Contains(key, StringComparer.CurrentCultureIgnoreCase))
-            {
-
-                throw Oops.Bah("没权限修改{key}");
-            }
-            var value = JObject.Parse(item.Value.ToString());
-            if (!value.ContainsKey("id"))
-            {
-
-                throw Oops.Bah("未传主键id");
-            }
-
-            var dt = new Dictionary<string, object>();
-            foreach (var f in value)
-            {
-                if (f.Key.ToLower() != "id" && _selectTable.IsCol(key, f.Key) && (role.Update.Column.Contains("*") || role.Update.Column.Contains(f.Key, StringComparer.CurrentCultureIgnoreCase)))
-                {
-                    dt.Add(f.Key, f.Value.ToString());
-                }
-            }
-            _db.Updateable(dt).AS(key).Where("id=@id", new { id = value["id"].ToString() }).ExecuteCommand();
-            ht.Add(key, JToken.FromObject(new { code = 200, msg = "success", id = value["id"].ToString() }));
+            int count = _selectTable.UpdateSingleTable(tableName,table.Value,role);
+            ht.Add(tableName, JToken.FromObject(new { count }));
         }
 
         return ht;
@@ -230,6 +210,10 @@ public class APIJSONService : IDynamicApiController, ITransient
                 }
 
             }
+            if (!parameters.Any())
+            {
+                throw Oops.Bah("请输入删除条件");
+            }
             string whereSql = sb.ToString().TrimEnd(" and ");
             int count = _db.Deleteable<object>().AS(talbeName).Where(whereSql, parameters).ExecuteCommand();//无实体删除
             value.Add("count", count);//命中数量

+ 1 - 1
Admin.NET/Admin.NET.Core/Service/APIJSON/IdentityService.cs

@@ -46,7 +46,7 @@ public class IdentityService : ITransient
     /// <returns></returns>
     public APIJSON_Role GetRole()
     {
-        var role = new APIJSON_Role();
+        APIJSON_Role role;
         if (string.IsNullOrEmpty(GetUserRoleName())) // 若没登录默认取第一个
         {
             role = _roles.FirstOrDefault();

+ 77 - 5
Admin.NET/Admin.NET.Core/Service/APIJSON/SelectTable.cs

@@ -13,9 +13,12 @@ using AspectCore.Extensions.Reflection;
 using NewLife.Data;
 using Newtonsoft.Json.Linq;
 using Newtonsoft.Json.Schema;
+using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
+using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
 using SqlSugar;
 using StackExchange.Redis;
 using System;
+using System.Collections;
 using System.Collections.Generic;
 using System.Dynamic;
 using System.Linq;
@@ -862,11 +865,12 @@ public class SelectTable : ISingleton
     /// <param name="tableName"></param>
     /// <param name="cols"></param>
     /// <param name="role"></param>
-    /// <returns></returns>
-    public object InsertSingle(string tableName,JObject cols,APIJSON_Role role)
+    /// <returns>(各种类型的)id</returns>
+    public object InsertSingle(string tableName, JObject cols, APIJSON_Role role = null)
     {
+        role ??= _identitySvc.GetRole();
         var dt = new Dictionary<string, object>();
-        
+
         foreach (var f in cols)//遍历字段
         {
             if (//f.Key.ToLower() != "id" &&   //是否一定要传id
@@ -878,15 +882,83 @@ public class SelectTable : ISingleton
         object id;
         if (!dt.ContainsKey("id"))
         {
-            id = YitIdHelper.NextId();
+            id = YitIdHelper.NextId();//自己生成id的方法,可以由外部传入
             dt.Add("id", id);
         }
         else
         {
             id = dt["id"];
         }
-         _db.Insertable(dt).AS(tableName).ExecuteCommand();//根据主键类型设置返回雪花或自增,目前返回条数
+        _db.Insertable(dt).AS(tableName).ExecuteCommand();//根据主键类型设置返回雪花或自增,目前返回条数
 
         return id;
     }
+    /// <summary>
+    /// 为每天记录创建udpate sql
+    /// </summary>
+    /// <param name="tableName"></param>
+    /// <param name="record"></param>
+    /// <param name="role"></param>
+    /// <returns></returns>
+    public int UpdateSingleRecord(string tableName, JObject record, APIJSON_Role role = null)
+    {
+        role ??= _identitySvc.GetRole();
+        if (!record.ContainsKey("id"))
+        {
+            throw Oops.Bah("未传主键id");
+        }
+        var dt = new Dictionary<string, object>();
+        var sb = new StringBuilder(100);
+        object id = null;
+        foreach (var f in record)//遍历每个字段
+        {
+            if (f.Key.Equals("id", StringComparison.OrdinalIgnoreCase))
+            {
+                if (f.Value is JArray)//id数组
+                {
+                    sb.Append($"{f.Key} in (@{f.Key})");
+                    id = FuncList.TransJArrayToSugarPara(f.Value);
+                  
+                }
+                else//单个id
+                {
+                    sb.Append($"{f.Key}=@{f.Key}");
+                   id = FuncList.TransJObjectToSugarPara(f.Value);
+                }
+            }
+            else if (IsCol(tableName, f.Key) && (role.Update.Column.Contains("*") || role.Update.Column.Contains(f.Key, StringComparer.CurrentCultureIgnoreCase)))
+            {
+                dt.Add(f.Key, FuncList.TransJObjectToSugarPara(f.Value));
+            }
+        }
+        string whereSql = sb.ToString();
+        int count = _db.Updateable(dt).AS(tableName).Where(whereSql, new { id }).ExecuteCommand();
+        return count;
+    }
+
+    /// <summary>
+    /// 更新单表,支持同表多条记录
+    /// </summary>
+    /// <param name="tableName"></param>
+    /// <param name="records"></param>
+    /// <param name="role"></param>
+    /// <returns></returns>
+    public int UpdateSingleTable(string tableName, JToken records, APIJSON_Role role = null)
+    {
+        role ??= _identitySvc.GetRole();
+        int count =0;
+        if (records is JArray)//遍历每行记录
+        {
+            foreach (var record in records.ToObject<JObject[]>())
+            {
+                count += UpdateSingleRecord(tableName, record, role);
+            }          
+        }
+        else//单条记录
+        {
+            count = UpdateSingleRecord(tableName, records.ToObject<JObject>(), role);
+        }
+
+        return count;
+    }
 }