/// <summary> /// Edit Habit entity /// </summary> /// <param name="viewHabit">Habit with changed fields</param> /// <param name="checkinLastDaysAmount">Amount last checkins in Habit Entity</param> /// <returns>Changed Habit if editing is happened and null if not</returns> public async Task<Habit> EditHabit(Habit viewHabit, int checkinLastDaysAmount = 0) { var dateRange = GetStartAndEndDatesForLastAmountDays(checkinLastDaysAmount); //TODO need split to 2 query. Checkins need get as NoTracking, them may be a lot var habitCheckinsList = await _dbContext.Habits .Where(h => h.UserId == _userId) .GroupJoin(_dbContext.Checkins.Where(ch => ch.Date >= dateRange.StartDate && ch.Date <= dateRange.EndDate), h => h.Id, checkin => checkin.HabitId, (h, checkins) => new { Habit = h, Checkins = checkins }) .FirstOrDefaultAsync(hc => hc.Habit.Id == viewHabit.Id); var dbHabit = habitCheckinsList.Habit; if (dbHabit == null) return null; dbHabit.Name = viewHabit.Name; await _dbContext.SaveChangesAsync(); var checkinsResult = GetFullCheckinArray(dbHabit.Id, habitCheckinsList.Checkins, dateRange.StartDate, dateRange.EndDate); dbHabit.Checkins = checkinsResult.ToList(); return dbHabit; }
/// <summary> /// Create new Habit /// </summary> /// <param name="viewHabit">Habit for saving, Id have to be equal 0</param> /// <param name="checkinLastDaysAmount">Amount last checkins in Habit Entity</param> /// <returns>Habit if creating is happened and null if not</returns> public async Task<Habit> CreateHabit(Habit viewHabit, int checkinLastDaysAmount = 0) { //we create new entity if only Id equal 0 if (viewHabit.Id != 0) return null; var dbHabit = new Habit(viewHabit.Name, _userId); _dbContext.Habits.Add(dbHabit); await _dbContext.SaveChangesAsync(); var dateRange = GetStartAndEndDatesForLastAmountDays(checkinLastDaysAmount); var checkinEmptyList = new List<Checkin>().AsEnumerable(); dbHabit.Checkins = GetFullCheckinArray(dbHabit.Id, checkinEmptyList, dateRange.StartDate, dateRange.EndDate).ToList(); return dbHabit; }