Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using Inviser.GeneratedModels;
- using Inviser.Services.DataDownloader;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Logging;
- namespace Inviser.Services
- {
- public class InvestmentRecordsUpdater
- {
- private readonly DataDownloaderRepository _dataDownloaderRepository;
- private readonly GeneratedInviserContext _context;
- private readonly ILogger<InvestmentRecordsUpdater> _logger;
- public InvestmentRecordsUpdater(
- DataDownloaderRepository dataDownloaderRepository,
- GeneratedInviserContext context,
- ILogger<InvestmentRecordsUpdater> logger
- ) {
- _dataDownloaderRepository = dataDownloaderRepository;
- _context = context;
- _logger = logger;
- }
- public async Task UpdateRecordsAsync()
- {
- var investments = await _context.Investment.ToListAsync();
- foreach (var investment in investments)
- {
- IDataDownloader dataDownloader = _dataDownloaderRepository.GetBySource(investment.Source);
- if (dataDownloader == null)
- {
- _logger.LogError("Missing {Downloader} for {Source}", nameof(IDataDownloader), investment.Source);
- continue;
- }
- _logger.LogInformation("Updating data for {Investment}", investment.Symbol);
- IEnumerable<InvestmentRecord> data = await dataDownloader.GetDataAsync(investment.Symbol);
- using (var transaction = await _context.Database.BeginTransactionAsync())
- {
- try
- {
- foreach (InvestmentRecord record in data)
- {
- record.Investment = investment;
- record.InvestmentId = investment.Id;
- await _context.InvestmentRecord.AddAsync(record);
- _context.Entry(record.Investment).State = EntityState.Unchanged;
- }
- await _context.SaveChangesAsync();
- transaction.Commit();
- }
- catch (Exception e)
- {
- transaction.Rollback();
- _context.ResetContextState();
- _logger.LogError(e, "Could not add records for {Investment}", investment.Name);
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement