using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using EnVisage.Models; namespace EnVisage.Code.BLL { public class StrategicGoalManager : ManagerBase { public StrategicGoalManager(EnVisageEntities dbContext) : base(dbContext) { } protected override StrategicGoal InitInstance() { return new StrategicGoal { Id = Guid.NewGuid() }; } protected override StrategicGoal RetrieveReadOnlyById(Guid key) { return DataTable.AsNoTracking().FirstOrDefault(t => t.Id == key); } public override DbSet DataTable { get { return DbContext.StrategicGoals; } } public override StrategicGoal Save(StrategicGoalModel model) { var goal = base.Save(model); if (model.Id == Guid.Empty) goal.Id = Guid.NewGuid(); var oldGoal2Companies = DbContext.StrategicGoal2Company.Where(x => x.StrategicGoalId == goal.Id).ToList(); var oldGoalCompaniesIds = oldGoal2Companies.Select(x => x.CompanyId); foreach (var t in oldGoal2Companies) { if (!model.CompanyId.Contains(t.CompanyId)) DbContext.StrategicGoal2Company.Remove(t); } foreach (var companyId in model.CompanyId.Except(oldGoalCompaniesIds)) { DbContext.StrategicGoal2Company.Add(new StrategicGoal2Company() { Id = Guid.NewGuid(), CompanyId = companyId, StrategicGoalId = goal.Id }); } return goal; } public List GetStrategicGoalsForProject(Guid projectId) { List results = new List(); var listofIds = this.DbContext.StrategicGoal2Project.Where(x => x.ProjectId == projectId).ToList(); foreach (StrategicGoal2Project link in listofIds) { results.Add(link.StrategicGoal); } return results; } public StrategicGoalModel GetStrategicGoalById(Guid? id) { if (!id.HasValue) return null; return StrategicGoalModelQueryBase.FirstOrDefault(x => x.Id == id); } public StrategicGoalModel GetStrategicGoalByName(string name) { return StrategicGoalModelQueryBase.FirstOrDefault(x => x.Name == name); } public IQueryable GetStrategicGoals() { return StrategicGoalModelQueryBase; } #region Queries private IQueryable StrategicGoalModelQueryBase { get { var query = DataTable.Select(x => new StrategicGoalModel() { Id = x.Id, Name = x.Name, Description = x.Description, StartDate = x.StartDate, EndDate = x.EndDate, Color = x.Color, NbrProjects = x.StrategicGoal2Project.Count, CompanyId = x.StrategicGoal2Company.Select(s => s.CompanyId).ToList() }); return query; } } #endregion } }