C#:如何使用API数据重构数据库连接方法并移除数据库依赖
Let's break down how to solve your two requirements with clear, updated code and explanations:
1. Modify GenerateRequestUri for Dynamic mapCode
First, we'll update this method to accept a mapCode parameter instead of using the hardcoded id=16. This lets you pass the dynamic value from your original method directly into the API request.
// Updated to use dynamic mapCode instead of fixed id=16 string GenerateRequestUri(string endpoint, int mapCode) { string requestUri = endpoint; requestUri += $"?id={mapCode}"; // Inject the passed mapCode into the query string return requestUri; }
2. Rewrite DataBaseConnection to Use API Data
We'll replace all database-specific logic with API calls, map the API response to your AlertLevel objects, and keep consistent error handling. I've renamed the method to reflect its new purpose (you can keep the original name if you need backward compatibility).
// Renamed for clarity (use original name DataBaseConnection if required) public IEnumerable<AlertLevel> GetAlertLevelsFromApi(int mapCode) { var listAlert = new List<AlertLevel>(); try { // Generate API URIs using the dynamic mapCode string stationsUri = GenerateRequestUriStations(Constants.EndPoint); string dataUri = GenerateRequestUri(Constants.EndPoint, mapCode); // Fetch data from your existing API service var result = _restServiceData.GetWaterDataForecast(stationsUri, dataUri); // Map API response items to AlertLevel objects (with null checks to avoid crashes) if (result?.WaterData?.Ardaforecast?.FirstOrDefault()?.Items != null) { foreach (var item in result.WaterData.Ardaforecast[0].Items) { listAlert.Add(new AlertLevel { dateForecast = item.DateTimeForecast, levelForecast = item.AlertLevelForecast }); } } } catch (Exception ex) { // Updated error message to reflect API failure instead of database issues Console.WriteLine("API Request Failed", $"Could not retrieve alert data: {Environment.NewLine}{ex.ToString()}", "OK"); } return listAlert; }
Key Changes Explained:
- Removed Database Dependencies: All MySQL connection/query code is replaced with calls to your existing
_restServiceDataAPI client. - Data Mapping: Directly maps
item.DateTimeForecastanditem.AlertLevelForecastfrom the API response to yourAlertLevelproperties. - Null Safety: Added checks to avoid
NullReferenceExceptionif the API returns unexpected null values in the response hierarchy. - Consistent Error Handling: Kept the same error logging pattern but updated the message to match the new API-focused logic.
If you need to retain the original method name (DataBaseConnection), simply replace the entire body of that method with the code above.
内容的提问来源于stack exchange,提问作者Blagovest Pizhev

