67 lines
2.0 KiB
C#

namespace active_allocator.Helpers;
using Microsoft.EntityFrameworkCore;
using active_allocator.Entities;
using System.Diagnostics;
using System;
public class DataContext : DbContext
{
//protected readonly IConfiguration Configuration;
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
//Configuration = configuration;
}
/*protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// in memory database used for simplicity, change to a real db for production applications
options.UseInMemoryDatabase("TestDb");
}*/
public void AddAmountToAccount(int accoundId, decimal amount)
{
Account account = this.Accounts.Find(accoundId);
if (account != null)
{
account.Balance += amount;
this.Accounts.Update(account);
this.SaveChanges();
}
}
public void RecalculateAccountBalance(int id)
{
Account account = this.Accounts.Find(id);
decimal amount = account.InitialBalance;
List<Transaction> transactions = this.Transactions
.Include(t => t.DebitAccount)
.Include(t => t.CreditAccount)
.Where(t =>
(t.DebitAccount != null && t.DebitAccount.Id == id)
|| (t.CreditAccount != null && t.CreditAccount.Id == id))
.ToList();
foreach (Transaction t in transactions)
{
if (t.DebitAccount?.Id == id) {
amount -= t.Amount;
} else if (t.CreditAccount?.Id == id) {
amount += t.Amount;
}
}
account.Balance = amount;
this.Accounts.Update(account);
this.SaveChanges();
}
public DbSet<User> Users { get; set; }
public DbSet<Account> Accounts { get; set; }
public DbSet<Envelope> Envelopes { get; set; }
public DbSet<CurrencyType> CurrencyTypes { get; set; }
public DbSet<Operation> Operations { get; set; }
public DbSet<Transaction> Transactions { get; set; }
}