Untitled

 avatar
unknown
plain_text
a month ago
5.6 kB
6
Indexable
public async Task LoadMeteringPointsFromApiAsync(ApiService apiService)
{
    try
    {
        // Fetch data from the API
        var meteringPoints = await apiService.FetchMeteringPointsAsync();
        var connectionMapping = await apiService.FetchConnectionMeteringPointsAsync();

        // Dictionary to store Connection entities for efficient lookup
        var connectionEntities = new Dictionary<string, Connection>();

        // Create and save Connection entities
        foreach (var kvp in connectionMapping)
        {
            var connectionId = kvp.Key;

            // Check if the Connection already exists in the database
            var dbConnection = await this.Connections.FirstOrDefaultAsync(c => c.ConnectionId == connectionId);

            if (dbConnection == null)
            {
                // Create a new Connection entity if it doesn't exist
                dbConnection = new Connection
                {
                    ConnectionId = connectionId,
                    // Add additional properties for Connection if needed
                };
                await this.Connections.AddAsync(dbConnection);
            }

            // Add the Connection entity to the dictionary for later use
            connectionEntities[connectionId] = dbConnection;
        }

        // Save Connection entities
        await this.SaveChangesAsync();

        // Create and save MeteringPoint entities linked to their Connection
        foreach (var meteringPoint in meteringPoints)
        {
            // Check if the MeteringPoint already exists in the database
            var existingMeteringPoint = await this.MeteringPoints.FindAsync(meteringPoint.Id);

            if (existingMeteringPoint != null)
            {
                Console.WriteLine($"MeteringPoint with Id {meteringPoint.Id} already exists. Skipping.");
                continue;
            }

            // Find the ConnectionId for this MeteringPoint from the mapping
            var connectionId = connectionMapping
                .FirstOrDefault(kvp => kvp.Value.Any(mp => mp.Id == meteringPoint.Id))
                .Key;

            // Check if the connectionId exists in the mapping
            if (!string.IsNullOrEmpty(connectionId) && connectionEntities.TryGetValue(connectionId, out var dbConnection))
            {
                // Create a new MeteringPoint entity
                var dbMeteringPoint = new MeteringPoint
                {
                    Id = meteringPoint.Id,
                    ProductType = meteringPoint.ProductType,
                    MeteringPointType = meteringPoint.MeteringPointType,
                    RelatedMeteringPointId = meteringPoint.RelatedMeteringPointId,
                    MeterNumber = meteringPoint.MeterNumber,
                    ConnectionId = dbConnection.ConnectionId, // Link to the corresponding ConnectionId
                };

                // Add Channels

                if (meteringPoint.Channels != null)
                {
                    foreach (var channel in meteringPoint.Channels)
                    {
                        Channels.Add(new Channel
                        {
                            ChannelNumber = channel.ChannelNumber,
                            Unit = channel.Unit,
                            Direction = channel.Direction,
                            MeteringPointId = dbMeteringPoint.Id,
                        });
                    }

                    Console.WriteLine("channels added");
                }
                else
                {
                    Console.WriteLine("channels NOT added");
                }

                // Add MasterData if available
                if (meteringPoint.MasterData != null && meteringPoint.MasterData.Any())
                {
                    var dbMasterData = new MasterData
                    {
                        Status = meteringPoint.MasterData.FirstOrDefault()?.Status,
                        ContractedCapacity = meteringPoint.MasterData.FirstOrDefault()?.ContractedCapacity,
                        Address = meteringPoint.MasterData.FirstOrDefault()?.Address,
                        City = meteringPoint.MasterData.FirstOrDefault()?.City,
                        BpCode = meteringPoint.MasterData.FirstOrDefault()?.BpCode,
                        BpName = meteringPoint.MasterData.FirstOrDefault()?.BpName,
                        AuthorizedFrom = meteringPoint.MasterData.FirstOrDefault()?.AuthorizedFrom,
                        AuthorizedUntil = meteringPoint.MasterData.FirstOrDefault()?.AuthorizedUntil,
                        Source = meteringPoint.MasterData.FirstOrDefault()?.Source,
                        MeteringPointId = dbMeteringPoint.Id,
                    };

                    await this.MasterDatas.AddAsync(dbMasterData);
                    Console.WriteLine("masterdata added");
                }


                // Save the MeteringPoint entity to the database
                await this.MeteringPoints.AddAsync(dbMeteringPoint);
            }
            else
            {
                Console.WriteLine($"No Connection found for MeteringPointId: {meteringPoint.Id}");
            }
        }

        // Save all changes to the database
        await this.SaveChangesAsync();

        Console.WriteLine("Data successfully saved to the database.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error fetching or saving data: {ex.Message}");
    }
}
Leave a Comment