/// <summary> /// 通过查询条件修改指定列 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="kvs">属性和值的键值对。用法 DbKvs.New().Add("属性名", 值)</param> /// <param name="expression">查询条件,注意:不支持导航属性,如 "student => student.School.Id > 0" 将无法解析</param> /// <returns>受影响的记录数</returns> public int Update <T>(DbKvs kvs, Expression <Func <T, bool> > expression = null) { var entityInfo = MyEntityContainer.Get(typeof(T)); var setProperties = kvs.Where(kv => kv.Key != "Id").Select(kv => kv.Key); var includeProperties = entityInfo.Properties.Where(p => setProperties.Contains(p.Name)).ToList(); if (includeProperties.Count == 0) { return(0); } string sql; List <SqlParameter> parameters; if (expression == null) { sql = $"UPDATE [{entityInfo.TableName}] SET {string.Join(",", includeProperties.Select(p => $"{p.FieldName}=@{p.Name}"))} WHERE Id=@Id"; parameters = kvs.ToSqlParameters(); } else { //var whereExpressionVisitor = new WhereExpressionVisitor<T>(); //whereExpressionVisitor.Visit(expression); //var where = whereExpressionVisitor.GetCondition(); //var whereParameters = whereExpressionVisitor.GetParameters().ToSqlParameters(); var resolver = new ConditionResolver(entityInfo); resolver.Resolve(expression.Body); var where = resolver.GetCondition(); var whereParameters = resolver.GetParameters().ToSqlParameters(); parameters = kvs.ToSqlParameters(); parameters.AddRange(whereParameters); where = string.IsNullOrWhiteSpace(where) ? "1=1" : where; sql = $"UPDATE [{entityInfo.TableName}] SET {string.Join(",", includeProperties.Select(p => $"{p.FieldName}=@{p.Name}"))} WHERE {where}"; } using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var command = new SqlCommand(sql, conn); command.Parameters.AddRange(parameters.ToArray()); return(command.ExecuteNonQuery()); } }
public async Task <int> UpdateAsync <T>(int id, DbKvs kvs) { var entityInfo = MyEntityContainer.Get(typeof(T)); var setProperties = kvs.Where(kv => kv.Key != "Id").Select(kv => kv.Key); var includeProperties = entityInfo.Properties.Where(p => setProperties.Contains(p.Name)).ToList(); if (includeProperties.Count == 0) { return(0); } var sql = $"UPDATE [{entityInfo.TableName}] SET {string.Join(",", includeProperties.Select(p => $"{p.FieldName}=@{p.Name}"))} WHERE Id=@Id"; var parameters = kvs.ToSqlParameters(); parameters.Add(new SqlParameter("@Id", id)); using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var command = new SqlCommand(sql, conn); command.Parameters.AddRange(parameters.ToArray()); return(await command.ExecuteNonQueryAsync()); } }