public async Task <IActionResult> SaveConnection(SaveConnectionRequest request) { // int connectionId = request.ConnectionId; DatabaseTable[] tablesGivenToSaveToDatabase = request.Tables; //get connections to which to save tables var connection = await ctx.ConnectionTables.Where(connection => connection.ConnectionId == connectionId).FirstOrDefaultAsync(); var tablesStoredInApplicationDatabaseForThisConnection = await ctx.DatabaseTables.Where(t => t.ConnectionId == connectionId).Include(t => t.DatabaseColumns).ToListAsync(); foreach (DatabaseTable tableGivenToSaveToDatabase in tablesGivenToSaveToDatabase) { //get corresponding table from own database DatabaseTable tableStoredInApplicationDatabase = tablesStoredInApplicationDatabaseForThisConnection.Find(t => t == tableGivenToSaveToDatabase); //if no corresponding table is stored in application database for given connection create new table if (tableStoredInApplicationDatabase == null) { DatabaseTable newTable = new DatabaseTable { Name = tableGivenToSaveToDatabase.Name, Connection = connection, ConnectionId = connectionId, DatabaseColumns = tableGivenToSaveToDatabase.DatabaseColumns, NumberOfColumnsToGenerate = tableGivenToSaveToDatabase.NumberOfColumnsToGenerate }; try { await ctx.AddAsync(newTable); } catch (Exception e) { return(BadRequest(new { error = true, message = e.Message })); } } else { tableStoredInApplicationDatabase.CopyRelevantGenerationValues(tableGivenToSaveToDatabase); var columnsStoredInApplicationDatabase = tableStoredInApplicationDatabase.DatabaseColumns; var columnsGivenToSaveToDatabase = tableGivenToSaveToDatabase.DatabaseColumns; // For every column given to save, check if there is corresponding table, if there is none create new one, if not modify existing column to fit new one foreach (var columnGivenToSaveToDatabase in columnsGivenToSaveToDatabase) { //if there is no column add it var columnStoredInApplicationDatabase = columnsStoredInApplicationDatabase.Where(c => c == columnGivenToSaveToDatabase).FirstOrDefault(); // If there is no corresponding column for column that needs to be saved to database add the new column to the database if (columnStoredInApplicationDatabase == null) { columnsStoredInApplicationDatabase.Add(columnGivenToSaveToDatabase); continue; } // If corresponding table exists modify existing one to match new one columnStoredInApplicationDatabase.CopyRelevantGenerationValues(columnGivenToSaveToDatabase); } } } await ctx.SaveChangesAsync(); return(Ok(new { error = false, message = "Successfully saved" })); }