public decimal Drain(int SiteId, decimal Amount) { using (var context = new GridBankDb()) { var site = context.GridBankSites.Find(SiteId); if (site == null) { throw new Exception("Site not found!"); } var lastReading = site.Usages .OrderByDescending(x => x.TimeStamp) .FirstOrDefault(); var updatedPower = (lastReading != null && lastReading.CurrentPower > Amount ? lastReading.CurrentPower - Amount : 0); var usage = new Usage { IdGuid = Guid.NewGuid(), GridBankSiteId = SiteId, TimeStamp = DateTime.Now, CurrentPower = updatedPower, IsNew = true }; site.Usages.Add(usage); context.SaveChanges(); return(usage.CurrentPower); } }
public static void Create() { using (var context = new GridBankDb()) { context.GridBankSites.AddOrUpdate(x => x.Id, new GridBankSite { Id = 1, Description = "Hwy49-Harrisburg" }, new GridBankSite { Id = 2, Description = "Hwy29-Concord" } ); context.SaveChanges(); } }