using DataDomain; using DatamodelLibrary; using StockDAL.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StockDAL { public class StockRepository : IStockRepository { public void SaveStockMember(StockMember stockMember) { using (var context = new StockContext()) { var sm = context.Stocks.Add(stockMember); context.SaveChanges(); } } public void UpdateActualPrice(int id, decimal price) { using var context = new StockContext(); var entity = (from stk in context.Stocks where stk.Id == id select stk).FirstOrDefault(); entity.ActValue = price; entity.ActDate = DateTime.Today; context.SaveChanges(); } public void UpdateActualForSell(int id, int sellAmount, decimal sellPrice, DateTime sellDate) { using var context = new StockContext(); var entity = (from stk in context.Stocks where stk.Id == id select stk).FirstOrDefault(); var rest = entity.ActAmount - sellAmount; entity.ActAmount = rest < 0 ? 0 : rest; entity.SoldDate = DateTime.Today; entity.SoldValue = sellAmount * sellPrice; context.SaveChanges(); } public IEnumerable GetAllStocks() { using var context = new StockContext(); var output = context.Stocks; return output.ToList(); } public IEnumerable GetAllRemainingStocks() { using var context = new StockContext(); var output = (from stk in context.Stocks where stk.SoldDate == null || stk.ActAmount > 0 select stk).ToList(); return output; } public void RemoveAllStocks() { using var context = new StockContext(); context.Stocks.RemoveRange(GetAllStocks()); context.SaveChanges(); } public void InsertMany(List stockMembers) { using var context = new StockContext(); context.Stocks.AddRange(stockMembers); context.SaveChanges(); } public void RestoreStockMembers(List stockMembers) { using var context = new StockContext(); using var transaction = context.Database.BeginTransaction(); try { var stocksToRemove = context.Stocks; context.Stocks.RemoveRange(stocksToRemove); var insertStocks = stockMembers.Select(o => new StockMember { Id = 0, StockId = o.StockId, StockExtId = o.StockExtId, BuyDate = o.BuyDate, BuyValue = o.BuyValue, ActAmount = o.ActAmount, ActValue = o.ActValue, ActDate = o.ActDate, SoldValue = o.SoldValue, SoldDate = o.SoldDate, Comment = o.Comment, PostAmount = o.PostAmount }).ToList(); context.Stocks.AddRange(insertStocks); context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { throw new InvalidOperationException(ex.Message); } } } }