private void DistributeСounselors(List <Tuple <int, int, int> > table) { int GroupId, CounselorId; { var temp = table.First(x => x.Item3 == table.Max(y => y.Item3)); GroupId = temp.Item2; CounselorId = temp.Item1; } using (var context = new CampDatabase()) { var counselor = context.Counsellors.First(x => x.Id == CounselorId); counselor.GroupId = GroupId; context.SaveChanges(); } table.RemoveAll(x => x.Item1 == CounselorId || x.Item2 == GroupId); if (table.Count == 0) { return; } else { DistributeСounselors(table); } }
public void CreateOrUpdate(InterestBindingModel model) { using (var context = new CampDatabase()) { Interest interest = context.Interests.FirstOrDefault(rec => rec.interest == model.Interest && rec.Id != model.Id); if (interest != null) { throw new Exception("Уже есть такой интерес"); } if (model.Id.HasValue) { interest = context.Interests.FirstOrDefault(rec => rec.Id == model.Id); if (interest == null) { throw new Exception("Элемент не найден"); } } else { interest = new Interest(); context.Interests.Add(interest); } interest.interest = model.Interest; context.SaveChanges(); } }
public void Delete(CounsellorBindingModel model) { using (var context = new CampDatabase()) { using (var transaction = context.Database.BeginTransaction()) { try { // удаяем записи по опыту и интересвм при удалении вожатого context.CounsellorInterests.RemoveRange(context.CounsellorInterests.Where(rec => rec.CounsellorId == model.Id)); context.CounsellorExperience.RemoveRange(context.CounsellorExperience.Where(rec => rec.CounsellorId == model.Id)); Counsellor counsellor = context.Counsellors.FirstOrDefault(rec => rec.Id == model.Id); if (counsellor != null) { context.Counsellors.Remove(counsellor); context.SaveChanges(); } else { throw new Exception("Элемент не найден"); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } }
public void Calculate() { using (var context = new CampDatabase()) { var Counselors = context.Counsellors.ToList(); var Groups = context.Groups.ToList(); foreach (var councelor in Counselors) { if (councelor.GroupId != null) { Groups.RemoveAll(x => x.Id == councelor.GroupId); } } Counselors.RemoveAll(x => x.GroupId != null); if (Groups.Count > Counselors.Count) { throw new Exception("Недостаточно вожатых для всех групп"); } //<идВожатого,идГрупа,насколькоПодходитВожатый> List <Tuple <int, int, int> > table = new List <Tuple <int, int, int> >(); foreach (var c in Counselors) { foreach (var g in Groups) { table.Add(CreateScore(c.Id, g.Id)); } } DistributeСounselors(table); } }
public void CreateOrUpdate(ExperienceBindingModel model) { using (var context = new CampDatabase()) { Experience experience; if (model.Id.HasValue) { experience = context.Experience.FirstOrDefault(rec => rec.Id == model.Id); if (experience == null) { throw new Exception("Элемент не найден"); } } else { experience = new Experience(); context.Experience.Add(experience); } experience.CounsellorId = model.CounsellorId; experience.AgeFrom = model.AgeFrom; experience.AgeTo = model.AgeTo; experience.Years = model.Years; context.SaveChanges(); } }
public void Delete(ChildBindingModel model) { using (var context = new CampDatabase()) { using (var transaction = context.Database.BeginTransaction()) { try { // удаяем записи по интересам при удалении ребёнка context.ChildInterests.RemoveRange(context.ChildInterests.Where(rec => rec.ChildId == model.Id)); Child child = context.Children.FirstOrDefault(rec => rec.Id == model.Id); if (child != null) { context.Children.Remove(child); context.SaveChanges(); } else { throw new Exception("Элемент не найден"); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } }
public void CreateOrUpdate(GroupBindingModel model) { using (var context = new CampDatabase()) { using (var transaction = context.Database.BeginTransaction()) { Group group; if (model.Id.HasValue) { group = context.Groups.FirstOrDefault(rec => rec.Id == model.Id); if (group == null) { throw new Exception("Элемент не найден"); } } else { group = new Group(); context.Groups.Add(group); } //group.CounsellorId = model.CounsellorId == 0 ? group.CounsellorId : model.CounsellorId; group.Name = model.Name; group.Profile = model.Profile; context.SaveChanges(); if (model.Id.HasValue) { // нашли детей, входящих в эту группу var Children = context.Children.Where(rec => rec.GroupId == model.Id.Value).ToList(); // у каждого ребёнка изменили значение группы foreach (var child in Children) { child.GroupId = model.Id; } } // добавили новые foreach (var child in context.Children) { if (model.Children.ContainsKey(child.Id)) { child.GroupId = group.Id; } } if (model.CounselorId != 0 && model.CounselorId != null) { var Counselor = context.Counsellors.Where(x => x.Id == model.CounselorId).ToList()[0]; Counselor.GroupId = group.Id; } context.SaveChanges(); transaction.Commit(); } } }
public void CreateOrUpdate(GroupBindingModel model) { using (var context = new CampDatabase()) { using (var transaction = context.Database.BeginTransaction()) { Group group; if (model.Id.HasValue) { group = context.Groups.FirstOrDefault(rec => rec.Id == model.Id); if (group == null) { throw new Exception("Элемент не найден"); } } else { group = new Group(); context.Groups.Add(group); } group.CounsellorId = model.CounsellorId == 0 ? group.CounsellorId : model.CounsellorId; group.Name = model.Name; group.Profile = model.Profile; context.SaveChanges(); if (model.Id.HasValue) { // нашли детей, входящих в эту группу var Children = context.Children.Where(rec => rec.GroupId == model.Id.Value).ToList(); // у каждого ребёнка обнулили значение группы foreach (var child in Children) { //logic.DeleteChildFromGroup(child.Id); child.GroupId = 0; } } // добавили новые foreach (var child in model.Children) { context.Children.Add(new Child { GroupId = group.Id, Id = child.Key, }); context.SaveChanges(); } transaction.Commit(); } } }
public List <InterestViewModel> Read(InterestBindingModel model) { using (var context = new CampDatabase()) { return(context.Interests .Where(rec => model == null || rec.Id == model.Id) .Select(rec => new InterestViewModel { Id = rec.Id, Interest = rec.interest }) .ToList()); } }
//проверяем, свободен ли вожатый public bool CounsellorIsFree(int Id) { using (var context = new CampDatabase()) { foreach (Counsellor counsellor in context.Counsellors) { if (counsellor.Id == Id && counsellor.GroupId == null) { return(true); } } return(false); } }
//количество общих интересов группы и вожатого public int FindSameInterestsCount(int counsellorId, int groupId) { using (var context = new CampDatabase()) { int count = 0; foreach (var interest in context.CounsellorInterests) { if (interest.CounsellorId == counsellorId) { count += FindChildrenWithThisInterestCount(interest.InterestId, groupId); } } return(count); } }
public List <ExperienceViewModel> Read(ExperienceBindingModel model) { using (var context = new CampDatabase()) { return(context.Experience .Where(rec => model == null || rec.Id == model.Id || (rec.AgeFrom == model.AgeFrom && rec.AgeTo == model.AgeTo && rec.Years == model.Years && rec.CounsellorId == model.CounsellorId)) .Select(rec => new ExperienceViewModel { Id = rec.Id, AgeFrom = rec.AgeFrom, AgeTo = rec.AgeTo, Years = rec.Years }) .ToList()); } }
public void Match() { using (var context = new CampDatabase()) { foreach (var group in context.Groups) { if (FindCounsellor(group.Id) == -1) { throw new Exception("Недостаточно вожатых для всех групп"); } group.CounsellorId = FindCounsellor(group.Id); MessageBox.Show("Все вожатые распределены по группам"); } context.SaveChanges(); } }
public void Delete(ExperienceBindingModel model) { using (var context = new CampDatabase()) { Experience experience = context.Experience.FirstOrDefault(rec => rec.Id == model.Id); if (experience != null) { context.Experience.Remove(experience); context.SaveChanges(); } else { throw new Exception("Элемент не найден"); } } }
public void Delete(InterestBindingModel model) { using (var context = new CampDatabase()) { Interest interest = context.Interests.FirstOrDefault(rec => rec.Id == model.Id); if (interest != null) { context.Interests.Remove(interest); context.SaveChanges(); } else { throw new Exception("Элемент не найден"); } } }
// ищем количество детей с определённым интересом в группе public int FindChildrenWithThisInterestCount(int interestId, int groupId) { using (var context = new CampDatabase()) { int count = 0; foreach (var child in context.Children) { foreach (var interest in context.ChildInterests) { if (child.GroupId == groupId && child.Id == interest.ChildId && interest.InterestId == interestId) { count++; } } } return(count); } }
private Tuple <int, int, int> CreateScore(int counselorId, int groupId) { int score = 0; using (var context = new CampDatabase()) { var interesCounselor = context.CounsellorInterests.Where(x => x.CounsellorId == counselorId).ToList(); var childerenInGroup = context.Children.Where(x => x.GroupId == groupId).ToList(); var expCounselor = context.Experience.Where(x => x.CounsellorId == counselorId).ToList(); foreach (var child in childerenInGroup) { var interestChild = context.ChildInterests.Where(x => x.ChildId == child.Id).ToList(); score += CreateScoreChildCounselorInterest(interesCounselor, interestChild); score += CreateScoreChildCounselorAgeAndExp(expCounselor, child.Age); } return(Tuple.Create(counselorId, groupId, score)); } }
public List <GroupViewModel> Read(GroupBindingModel model) { using (var context = new CampDatabase()) { return(context.Groups .Where(rec => model == null || (rec.Id == model.Id && model.Id.HasValue)) .Select(rec => new GroupViewModel { Id = rec.Id, CounsellorId = context.Counsellors.Where(x => x.GroupId == rec.Id).First().Id, CounsellorName = context.Counsellors.Where(x => x.GroupId == rec.Id).First().FIO, Name = rec.Name, Profile = rec.Profile, }) .ToList()); } }
//средний возраст детей в группе public int FindAvarageChildrenAge(int groupId) { using (var context = new CampDatabase()) { int age = 0; int count = 0; foreach (Child child in context.Children) { if (child.GroupId == groupId) { age = age + child.Age; count++; } } return(age / count); } }
public List <GroupViewModel> Read(GroupBindingModel model) { using (var context = new CampDatabase()) { return(context.Groups .Include(rec => rec.children) .Where(rec => model == null || (rec.Id == model.Id && model.Id.HasValue) && (rec.Profile <= model.Profile)) .Select(rec => new GroupViewModel { Id = rec.Id, CounsellorId = rec.CounsellorId, Name = rec.Name, Profile = rec.Profile, }) .ToList()); } }
public List <ChildViewModel> Read(ChildBindingModel model) { using (var context = new CampDatabase()) { return(context.Children .Where(rec => model == null || rec.Id == model.Id || rec.GroupId == model.GroupId) .ToList() .Select(rec => new ChildViewModel { Id = rec.Id, FIO = rec.FIO, Age = rec.Age, ChildInterests = context.ChildInterests .Include(recPC => recPC.interest) .Where(recPC => recPC.ChildId == rec.Id) .ToDictionary(recPC => recPC.InterestId, recPC => recPC.interest?.interest) }) .ToList()); } }
//ищем наиболее подходящего свободного вожатого для группы public int FindCounsellor(int groupId) { using (var context = new CampDatabase()) { int id = -1; // индекс, который определяет, насколько подходит опыт работы к среднему возрасту детей = опыт работы*кол-во общих интересов / (разница возрастов + 1) int maxIndex = 0; foreach (Experience experience in context.Experience) { if (CounsellorIsFree(experience.CounsellorId)) { int index = experience.Years * FindSameInterestsCount(experience.CounsellorId, groupId) / (FindDiff(experience.AgeFrom, experience.AgeTo, FindAvarageChildrenAge(groupId)) + 1); if (index > maxIndex) { maxIndex = index; id = experience.CounsellorId; } } } return(id); } }
public List <CounsellorViewModel> Read(CounsellorBindingModel model) { using (var context = new CampDatabase()) { return(context.Children .Where(rec => model == null || rec.Id == model.Id) .ToList() .Select(rec => new CounsellorViewModel { Id = rec.Id, FIO = rec.FIO, GroupId = rec.GroupId, CounsellorInterests = context.CounsellorInterests .Include(recPC => recPC.counsellorInterests) .Where(recPC => recPC.CounsellorId == rec.Id) .ToDictionary(recPC => recPC.CounsellorId, recPC => recPC.counsellorInterests.interest), CounsellorExperience = context.CounsellorExperience .Include(recPC => recPC.counsellorExperience) .Where(recPC => recPC.CounsellorId == rec.Id) .ToDictionary(recPC => recPC.CounsellorId, recPC => (recPC.counsellorExperience.AgeFrom, recPC.counsellorExperience.AgeTo, recPC.counsellorExperience.Years)) })
public void Match() { using (var context = new CampDatabase()) { foreach (var group in context.Groups) { if (FindCounsellor(group.Id) == -1) { throw new Exception("Недостаточно вожатых для всех групп"); } //ищем вожатого с данным id и устанавливаем ему id группы foreach (var counsellor in context.Counsellors) { if (counsellor.Id == FindCounsellor(group.Id)) { counsellor.GroupId = group.Id; } } } MessageBox.Show("Все вожатые распределены по группам"); context.SaveChanges(); } }
public void Delete(GroupBindingModel model) { using (var context = new CampDatabase()) { Group group = context.Groups.FirstOrDefault(rec => rec.Id == model.Id); if (group != null) { // нашли детей, входящих в эту группу var Children = context.Children.Where(rec => rec.GroupId == model.Id.Value).ToList(); // у каждого ребёнка обнулили значение группы foreach (var child in Children) { child.GroupId = 0; } context.Groups.Remove(group); context.SaveChanges(); } else { throw new Exception("Элемент не найден"); } } }
public void CreateOrUpdate(ChildBindingModel model) { using (var context = new CampDatabase()) { using (var transaction = context.Database.BeginTransaction()) { try { Child child = context.Children.FirstOrDefault(rec => rec.FIO == model.FIO && rec.Id != model.Id); if (child != null) { throw new Exception("Уже есть ребёнок с таким именем"); } if (model.Id.HasValue) { child = context.Children.FirstOrDefault(rec => rec.Id == model.Id); if (child == null) { throw new Exception("Ребёнок не найден"); } } else { child = new Child(); context.Children.Add(child); } child.FIO = model.FIO; child.Age = model.Age; context.SaveChanges(); if (model.Id.HasValue) { var ChildInterests = context.ChildInterests.Where(rec => rec.ChildId == model.Id.Value).ToList(); // удалили те, которых нет в модели context.ChildInterests.RemoveRange(ChildInterests.Where(rec => !model.ChildInterests.ContainsKey(rec.InterestId)).ToList()); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateInterest in ChildInterests) { model.ChildInterests.Remove(updateInterest.InterestId); } context.SaveChanges(); } // добавили новые foreach (var interest in model.ChildInterests) { context.ChildInterests.Add(new ChildInterests { ChildId = child.Id, InterestId = interest.Key, }); context.SaveChanges(); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } }
public void CreateOrUpdate(CounsellorBindingModel model) { using (var context = new CampDatabase()) { using (var transaction = context.Database.BeginTransaction()) { try { Counsellor counsellor = context.Counsellors.FirstOrDefault(rec => rec.FIO == model.FIO && rec.Id != model.Id); if (counsellor != null) { throw new Exception("Уже есть вожатый с таким именем"); } if (model.Id.HasValue) { counsellor = context.Counsellors.FirstOrDefault(rec => rec.Id == model.Id); if (counsellor == null) { throw new Exception("Вожатый не найден"); } } else { counsellor = new Counsellor(); context.Counsellors.Add(counsellor); } counsellor.FIO = model.FIO; counsellor.GroupId = model.GroupId; context.SaveChanges(); if (model.Id.HasValue) { var CounsellorExperience = context.CounsellorExperience.Where(rec => rec.ExperienceId == model.Id.Value).ToList(); // удалили те, которых нет в модели context.CounsellorExperience.RemoveRange(CounsellorExperience.Where(rec => !model.CounsellorExperience.ContainsKey(rec.ExperienceId)).ToList()); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateExperience in CounsellorExperience) { model.CounsellorExperience.Remove(updateExperience.ExperienceId); } var CounsellorInterests = context.CounsellorInterests.Where(rec => rec.CounsellorId == model.Id.Value).ToList(); // удалили те, которых нет в модели context.CounsellorInterests.RemoveRange(CounsellorInterests.Where(rec => !model.CounsellorInterests.ContainsKey(rec.InterestId)).ToList()); context.SaveChanges(); // обновили количество у существующих записей foreach (var updateInterest in CounsellorInterests) { model.CounsellorInterests.Remove(updateInterest.InterestId); } context.SaveChanges(); } // добавили новые foreach (var interest in model.CounsellorInterests) { context.CounsellorInterests.Add(new CounsellorInterests { CounsellorId = counsellor.Id, InterestId = interest.Key, }); context.SaveChanges(); } foreach (var experience in model.CounsellorExperience) { context.CounsellorExperience.Add(new CounsellorExperience { CounsellorId = counsellor.Id, ExperienceId = experience.Key, }); context.SaveChanges(); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } } }