/// <summary> /// 执行数据库的更新操作 /// </summary> /// <param name="sql"></param> /// <param name="parameters"></param> /// <param name="dalHints"></param> /// <returns></returns> private async Task <ExecutionResult> ExecuteNonQuery(string sql, List <DatabaseParameter> parameters, DalHints dalHints) { using (var conn = new MySqlConnection(GetConnectionString())) { // 打开数据库链接 await conn.OpenAsync(); using (var command = BuildCommand(sql, parameters, conn)) { var result = new ExecutionResult() { // 执行Sql语句 ReturnCode = await command.ExecuteNonQueryAsync() }; // 是否需要设置传回主键 if (DalHints.IsSet(dalHints, DalHint.SetIdentity)) { using (var identityCommand = new MySqlCommand("SELECT @@Identity;", conn)) { result.Identity = (ulong)await identityCommand.ExecuteScalarAsync(); } } return(result); } } }
public async Task <int> Insert <T>(T entity) where T : class, new() { // 获取组装好的sql和参数 (string sql, List <DatabaseParameter> parameters) = SqlBuilderFactory.GetInstance <T>().BuildInsert(entity); var client = DalClientFactory.GetClient(GetLogicDatabaseName <T>()); // 将主键返回给实体 var hints = DalHints.Create(); // 如果当前实例含有自增主键,且自增主键的实体不为空,那么需要数据库返回自增住居 var identity = EntityMetaDataMapper.GetInstance().Get <T>().Columns.Find(p => p.Attribute.Identity); if (identity != null && identity.Attribute.Identity && identity.ColumnProperty.GetValue(entity) == null) { hints.Add(DalHint.SetIdentity); } var result = await client.Execute(sql, parameters, hints); // 如果数据库返回了主键,那么将主键设置回实体 // 暂时先这么写 if (result.Identity > 0) { if (identity.ColumnProperty.PropertyType == typeof(int?)) { int.TryParse(result.Identity.ToString(), out var value); identity.ColumnProperty.SetValue(entity, value); } else { long.TryParse(result.Identity.ToString(), out var value); identity.ColumnProperty.SetValue(entity, value); } } return(result.ReturnCode); }
public async Task <ExecutionResult> Execute(string sql, List <DatabaseParameter> parameters, DalHints dalHints) { return(await ExecuteNonQuery(sql, parameters, dalHints)); }