Example #1
0
        public static bool UpdateTeacher(Teacher _userToEdit, Address _addressToEdit)
        {
            bool done = false;

            using (var myDB = new VirtualCollegeContext())
            {
                var students = myDB.Users.
                               Include("Lessons").
                               Include("PresentLessons").
                               OfType <Student>().
                               ToList();

                var teachers = myDB.Users.
                               Include("Courses").
                               OfType <Teacher>().ToList();

                var courses = myDB.Courses.
                              Include("Teachers").
                              ToList();

                var lessons = myDB.Lessons.
                              Include("Students").
                              Include("PresentStudents").
                              ToList();

                var grades          = myDB.Grades.ToList();
                var payments        = myDB.Payments.ToList();
                var addresses       = myDB.Addresses.ToList();
                var teacherToModify = teachers.Find(s => s.UserId == _userToEdit.UserId);
                var oldAddress      = addresses.Find(a => a.AddressId == teacherToModify.Address.AddressId);

                if (_addressToEdit.AddressLine2 == "")
                {
                    _addressToEdit.AddressLine2 = null;
                }

                var     desc  = _addressToEdit.ToString();
                Address match = addresses.Find(a => a.ToString() == desc);

                if (match == null)
                {
                    myDB.Addresses.Add(new Address()
                    {
                        AddressLine1 = _addressToEdit.AddressLine1,
                        AddressLine2 = _addressToEdit.AddressLine2,
                        Postcode     = _addressToEdit.Postcode,
                        City         = _addressToEdit.City,
                        State        = _addressToEdit.State,
                        Country      = _addressToEdit.Country
                    });
                    myDB.SaveChanges();
                    addresses = myDB.Addresses.ToList();
                    teacherToModify.Address = addresses[addresses.Count - 1];
                }
                else
                {
                    teacherToModify.Address = addresses.Find(a => a.AddressId == match.AddressId);
                }

                teacherToModify.EmailAddress = _userToEdit.EmailAddress;
                teacherToModify.Password     = _userToEdit.Password;
                teacherToModify.PhoneNumber  = _userToEdit.PhoneNumber;

                if (oldAddress.Users.Count == 0)
                {
                    myDB.Addresses.Remove(oldAddress);
                }

                done = true;
                myDB.SaveChanges();
            }
            return(done);
        }