public TrendIndex GetTrendIndex(string sector, PriceBarSize priceBarSize, int swingPointBarCount, bool create = true) { using (var db = new IndexDatabaseContext()) { var ret = (from index in db.TrendIndices.AsNoTracking().Include(x => x.IndexEntries) where index.IndexName == sector where index.IndexSwingpointBarCount == swingPointBarCount where index.TrendPriceBarSize == priceBarSize select index).FirstOrDefault(); if (ret != null || !create) return ret; db.TrendIndices.Add(new TrendIndex(sector, swingPointBarCount, priceBarSize)); db.SaveChanges(); ret = (from index in db.TrendIndices.AsNoTracking().Include(x => x.IndexEntries) where index.IndexName == sector where index.IndexSwingpointBarCount == swingPointBarCount where index.TrendPriceBarSize == priceBarSize select index).FirstOrDefault(); if (ret == null) Console.WriteLine(); return ret; } }
public void SetTrendIndex(TrendIndex trendIndex) { if (trendIndex == null) return; using (var db = new IndexDatabaseContext()) { // Get the index entity stored in the database var dbIndex = (from index in db.TrendIndices where index.IndexName == trendIndex.IndexName //where index.IndexSwingpointBarCount == trendIndex.IndexSwingpointBarCount //where index.TrendPriceBarSize == trendIndex.TrendPriceBarSize select index).FirstOrDefault(); if (dbIndex == null) { throw new SecurityNotFoundException() { message = "Attempted to reattach non-existent index to database" }; } // Update scalar properties of Security db.Entry(dbIndex).CurrentValues.SetValues(trendIndex); foreach (var newIndexDay in trendIndex.IndexEntries) { // Find existing bar if one exists for this date var currentIndexDay = dbIndex.IndexEntries.SingleOrDefault(x => x == newIndexDay); if (currentIndexDay != null) { // Update bars that are in the new bar collection db.Entry(currentIndexDay).CurrentValues.SetValues(newIndexDay); } else { // Insert new bars newIndexDay.Parent = dbIndex; dbIndex.IndexEntries.Add(newIndexDay); } } db.SaveChanges(); } }