You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#:如何使用API数据重构数据库连接方法并移除数据库依赖

Solution: Replace Database Connection with API Data Fetching

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 _restServiceData API client.
  • Data Mapping: Directly maps item.DateTimeForecast and item.AlertLevelForecast from the API response to your AlertLevel properties.
  • Null Safety: Added checks to avoid NullReferenceException if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:02:52