From 2d46d11c9cb1a6b45436829b384963add4c6b2a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A7=E7=9F=B3=E5=A4=B4?= Date: Wed, 1 Nov 2023 15:22:36 +0800 Subject: [PATCH] =?UTF-8?q?DAL.Update=E6=94=AF=E6=8C=81=E5=AD=97=E5=85=B8?= =?UTF-8?q?=E3=80=82close=20https://github.com/NewLifeX/NewLife.XCode/issu?= =?UTF-8?q?es/16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- XCode/DataAccessLayer/DAL_Mapper.cs | 46 ++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/XCode/DataAccessLayer/DAL_Mapper.cs b/XCode/DataAccessLayer/DAL_Mapper.cs index dd5125e39..75899ef38 100644 --- a/XCode/DataAccessLayer/DAL_Mapper.cs +++ b/XCode/DataAccessLayer/DAL_Mapper.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; +using System.Collections.Concurrent; using System.Data; using System.Data.Common; -using System.Linq; using System.Reflection; -using System.Threading.Tasks; using NewLife; using NewLife.Collections; using NewLife.Data; @@ -304,8 +300,23 @@ public Int32 Update(Object data, Object where, String? tableName = null) sb.Append("Update "); sb.Append(tableName); + var dic = data as IDictionary; var dps = new List(); // Set参数 + if (dic != null) + { + sb.Append(" Set "); + var i = 0; + foreach (var item in dic) + { + if (i++ > 0) sb.Append(','); + + var p = Db.CreateParameter(item.Key, item.Value, item.Value?.GetType()); + dps.Add(p); + sb.AppendFormat("{0}={1}", item.Key, p.ParameterName); + } + } + else { sb.Append(" Set "); var i = 0; @@ -337,14 +348,27 @@ public Int32 Update(Object data, Object where, String? tableName = null) var name = OnGetKeyName(data.GetType()); if (name.IsNullOrEmpty()) name = "Id"; - var pi = data.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); - if (pi == null) throw new XCodeException($"更新实体对象时未标记主键且未设置where"); + if (dic != null) + { + if (!dic.TryGetValue(name, out var val)) throw new XCodeException($"更新实体对象时未标记主键且未设置where"); - sb.Append(" Where "); + sb.Append(" Where "); - var p = Db.CreateParameter(pi.Name, pi.GetValue(data, null), pi.PropertyType); - dps.Add(p); - sb.AppendFormat("{0}={1}", pi.Name, p.ParameterName); + var p = Db.CreateParameter(name, val, val?.GetType()); + dps.Add(p); + sb.AppendFormat("{0}={1}", name, p.ParameterName); + } + else + { + var pi = data.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); + if (pi == null) throw new XCodeException($"更新实体对象时未标记主键且未设置where"); + + sb.Append(" Where "); + + var p = Db.CreateParameter(pi.Name, pi.GetValue(data, null), pi.PropertyType); + dps.Add(p); + sb.AppendFormat("{0}={1}", pi.Name, p.ParameterName); + } } var sql = sb.Put(true);