Example #1
0
        public async Task <IActionResult> Create([Bind("ID,CourseId,Title,Body")] Lecture lecture)
        {
            lecture.UpdateTime = DateTime.Now;

            var notification = new Notification();

            notification.Time   = DateTime.Now;
            notification.UserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            notification.Body   = " has added a new lecture: <i>" + lecture.Title + "</i>";

            var enrollments = _context.Enrollments
                              .Where(e => e.CourseID == lecture.CourseId)
                              .Select(s => s.Student.UserID)
                              .AsNoTracking()
                              .ToList();

            if (enrollments != null)
            {
                foreach (var enrollment in enrollments)
                {
                    var UserNotification = new UserNotification();
                    UserNotification.UserId       = enrollment;
                    UserNotification.Notification = notification;

                    _context.UserNotifications.Add(UserNotification);
                }
            }


            if (ModelState.IsValid)
            {
                _context.Add(lecture);
                _context.Notifications.Add(notification);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(lecture));
        }
        public async Task <IActionResult> Create(SchoolManagement.Models.StudentMgmt.StuCreate student)
        {
            if (ModelState.IsValid)
            {
                var belongs = _context.Specialty.SingleOrDefault(q => q.Name == student.SpecialtyName);
                if (belongs != null)
                {
                    var stu = new Student()
                    {
                        Name     = student.Name,
                        Sex      = student.Sex,
                        Password = "******",
                        belongs  = belongs
                    };
                    _context.Add(stu);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            return(View(student));
        }
Example #3
0
        public async Task <IActionResult> Create([Bind("FirstMidName,HireDate,LastName,OfficeAssignment")] Instructor instructor, string[] selectedCourses)
        {
            if (selectedCourses != null)
            {
                instructor.Courses = new List <CourseAssignment>();
                foreach (var course in selectedCourses)
                {
                    var courseToAdd = new CourseAssignment {
                        InstructorID = instructor.ID, CourseID = int.Parse(course)
                    };
                    instructor.Courses.Add(courseToAdd);
                }
            }
            if (ModelState.IsValid)
            {
                _context.Add(instructor);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(instructor));
        }
Example #4
0
        public async Task <IActionResult> Create(
            [Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(student);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(View(student));
        }
        public async Task <IActionResult> Create([Bind("LastName,FirstMidName,HireDate,OfficeAssignment")] Instructor instructor, string[] selectedCourses)
        {
            if (selectedCourses != null)
            {
                instructor.CourseAssignments = selectedCourses.Select(course => new CourseAssignment
                {
                    InstructorID = instructor.ID,
                    CourseID     = int.Parse(course)
                }).ToList();
            }

            if (ModelState.IsValid)
            {
                _context.Add(instructor);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            PopulateAssignedCourseData(instructor);
            return(View(instructor));
        }
Example #6
0
        static Guid InsertCourseWithStudents()
        {
            var course = new Course
            {
                Id          = Guid.NewGuid(),
                Number      = "COMP3717",
                Description = "Android Development",
                Room        = new Room
                {
                    Building   = "SE12",
                    RoomNumber = 322
                },
                Students = new List <Student>()
                {
                    new Student {
                        StudentId = "A00111111",
                        FirstName = "Bob",
                        LastName  = "Fox",
                        Gender    = "Male"
                    },
                    new Student {
                        StudentId = "A00222222",
                        FirstName = "Ann",
                        LastName  = "Fay",
                        Gender    = "Female"
                    }
                }
            };

            using (var context = new SchoolContext())
            {
                context.Database.EnsureCreated();
                context.Add(course);
                context.SaveChanges();
            }

            return(course.Id);
        }
Example #7
0
        public async Task <IActionResult> Create(StudentDto student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var stu = new Student();
                    stu.Name       = student.Name;
                    stu.EnrollDate = student.EnrollDate;

                    _context.Add(stu);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("CreateError", "保存数据失败!原因:" + ex.Message);
            }

            return(View(student));
        }
        public async Task <IActionResult> Create(
            [Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newStudent = student;
                    _logger.LogInformation(message: "We are about to add this person: " + student.FullName + " Enrollment date: " + student.EnrollmentDate);
                    _context.Add(student);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException ex)
            {
                //Log the error (uncomment ex variable name and write a log.
                _logger.LogError(message: "Unable to save changes. It Ocurred an error. Details:" + ex);
                ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "destroy your computer.");
            }
            return(View(student));
        }
        public async Task <IActionResult> Create(
            [Bind("CourseID,Credits,DepartmentID,Title")] Course course)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(course);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            PopulateDepartmentsDropDownList(course.DepartmentID);
            return(View(course));
        }
Example #10
0
        public async Task <IActionResult> Create(SchoolManagement.Models.LesnMgmt.LesnCreate lesson)
        {
            if (ModelState.IsValid)
            {
                var spl = await _context.Specialty.SingleOrDefaultAsync(q => q.Name == lesson.SpecialtyName);

                if (spl != null)
                {
                    var lesn = new Lesson()
                    {
                        Name    = lesson.Name,
                        Hour    = lesson.Hour,
                        Credit  = lesson.Credit,
                        Belongs = spl
                    };
                    _context.Add(lesn);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            return(View(lesson));
        }
        //a model binder converts posted form values to CLR types and passes them to the action method in parameters.
        //In this case, the model binder instantiates a Student entity for you using property values from the Form collection.)
        //Removed ID paramepter as this is set by Sql Server.Input from the user does not set the ID value.
        public async Task <IActionResult> Create([Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Add the the student entity created by the model binder to the Students entity set and then save the changes
                    //to the database.Model Binder converts POSTED form values to Clr types and then passes them to the action method in parameters
                    _context.Add(student);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
            }
            return(View(student));
        }
        static void Main(string[] args)
        {
            using (var context = new SchoolContext())
            {
                var std = new Student()
                {
                    Name            = "Max",
                    Birthday        = new DateTime(2001, 2, 2),
                    Notendurschnitt = 3.4f
                };

                context.Students.Add(std);
                context.Add(std);


                //context.Database.BeginTransaction();
                //context.Database.CommitTransaction();
                //context.Database.RollbackTransaction();


                context.SaveChanges(); //Hier wird erst das SQL richtig DB gesendet
            }
        }
        public async Task <IActionResult> Create([Bind("Id,Title,Location,TeacherName")] Class @class, string[] selectedStudents)
        {
            if (selectedStudents != null)
            {
                @class.Enrollments = new List <Enrollment>();
                foreach (var student in selectedStudents)
                {
                    var StudentToAdd = new Enrollment {
                        ClassID = @class.Id, StudentID = int.Parse(student)
                    };
                    @class.Enrollments.Add(StudentToAdd);
                }
            }
            if (ModelState.IsValid)
            {
                _context.Add(@class);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            PopulateAssignedStudentData(@class);
            return(View(@class));
        }
Example #14
0
        static async Task Main(string[] args)
        {
            #region 新增一筆 person (Last Name: Lee , First Name : Vulcan)
            Person person = new Person()
            {
                LastName  = "Lee",
                FirstName = "Vulcan",
                HireDate  = DateTime.Now
            };
            context.Add(person);
            await context.SaveChangesAsync();

            Console.WriteLine($"Vulcan Lee 已經新增");
            ShowChangeTracking();
            #endregion

            #region 修改 person (Last Name: Lee , First Name : Avatar)
            Person searchPerson = await context.Person.FirstOrDefaultAsync(x => x.FirstName == "Vulcan");

            Console.WriteLine($"Vulcan Lee 已經查詢出來");
            ShowChangeTracking();
            Person updatePerson = searchPerson.Clone();
            updatePerson.LastName  = "Hu";
            updatePerson.FirstName = "Avatar";
            await DoModifyPerson(updatePerson);

            Console.WriteLine($"Vulcan Lee 已經更新為 Avatar Hu");
            ShowChangeTracking();
            #endregion

            #region 刪除 person (Last Name: Lee , First Name : Avatar)
            await DoDeletePerson(updatePerson);

            Console.WriteLine($"Avatar Hu 已經刪除");
            ShowChangeTracking();
            #endregion
        }
        public async Task <IActionResult> Create([Bind("Title,ParentID,NeedPassWord,PassWord,ID")] CategoryModel categoryModel)
        {
            ViewBag.isSuccess = null;
            var Category = new List <SelectListItem> {
                new SelectListItem()
                {
                    Text = "主目录", Value = "-1", Selected = true
                }
            };
            var allCategory = _context.Category.ToList();


            Category.AddRange(Tools.CreateTree(allCategory, -1, 0));
            //add
            for (int i = 0; i < Category.Count; i++)
            {
                if (Category[i].Value == categoryModel.ParentID.ToString())
                {
                    Category[i].Selected = true;
                }
            }
            //add
            ViewBag.CategoryType = Category;
            if (ModelState.IsValid)
            {
                _context.Add(categoryModel);
                await _context.SaveChangesAsync();

                ViewBag.isSuccess = true;
                return(View());
            }
            ViewBag.isSuccess = false;
            // add
            ViewBag.InputTitle = "";

            return(View(categoryModel));
        }
Example #16
0
        //public async Task<IActionResult> Create(
        //  [Bind("ID,LastName,FirstMidName,EnrollmentDate")] Student student
        //  )
        public async Task <IActionResult> Create(
            [Bind("LastName,FirstMidName,EnrollmentDate")] Student student
            )
        {
            //explicitly state the fields you want to fill, so that if new fields become avail. in the datamodel, they don't create confusion ;
            //also for security reasons - avoid overposting - tricked/"hacked"/"hijacked" posting - ao. ...
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(student);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException /* exc */)
            {
                //Log the err (uncomment var name exc in the above catch-spec & write a log)
                ModelState.AddModelError("", "Unable to save changes to DB \n" +
                                         "Try again, and if the problem persists see your system admin :( ");
            }
            return(View(student));
        }
Example #17
0
        public async Task <IActionResult> Create([Bind("FirstMidName,HireDate,LastName,OfficeAssignment")] Instructor instructor, string[] selectedCourses)
        {
            // HttpPost Create method adds each selected course to the CourseAssignments navigation property before it checks for validation errors and adds the new instructor to the database.
            if (selectedCourses != null)
            {
                instructor.CourseAssignments = new List <CourseAssignment>(); // add courses to the CourseAssignments navigation property you have to initialize the property as an empty collection:
                foreach (var course in selectedCourses)
                {
                    var courseToAdd = new CourseAssignment {
                        InstructorID = instructor.ID, CourseID = int.Parse(course)
                    };
                    instructor.CourseAssignments.Add(courseToAdd);
                }
            }
            if (ModelState.IsValid)
            {
                _context.Add(instructor);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            PopulateAssignedCourseData(instructor);
            return(View(instructor));
        }
Example #18
0
        public async Task <IActionResult> Create([Bind("ID,LastName,FirstMidName,HireDate,OfficeAssignment")] Instructor instructor, int[] selectedCourses) //可以绑定导航属性,即便是导航属性为复杂对象。
        {
            //对于1对0或1关系,在创建1方的代码中,通过模型绑定自动完成。更是无需使用关联数据。
            //对于1对多关系,需要先初始化一个空的列表,然后,新建一个导航属性的对象,加到内存中的模型绑定的对象的导航属性的列表上。直接_context.update(T),原实体和关联数据一起更新了。
            if (selectedCourses != null)
            {
                instructor.CourseAssignments = new List <CourseAssignment>(); //Notice that in order to be able to add courses to the CourseAssignments navigation property you have to initialize the property as an empty collection:
                foreach (var course in selectedCourses)
                {
                    var courseToAdd = new CourseAssignment {
                        InstructorID = instructor.ID, CourseID = course
                    };
                    instructor.CourseAssignments.Add(courseToAdd); //先把导航属性加到模型绑定创建的内存中的Instructor来。any course selections that were made are automatically restored.
                }
            }
            if (ModelState.IsValid)
            {
                _context.Add(instructor); //如果是直接创建,可以将Instructor和他导航属性字段一并保存到数据库。
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            PopulateAssignedCourseData(instructor);
            return(View(instructor));

            /*
             * if (ModelState.IsValid)
             * {
             *  _context.Add(instructor);
             *  await _context.SaveChangesAsync();
             *  return RedirectToAction(nameof(Index));
             * }
             *
             * return View(instructor); */
        }
Example #19
0
        public async Task <IActionResult> Create(SchoolManagement.Models.TchrMgmt.TchCreate teacher)
        {
            if (ModelState.IsValid)
            {
                var clg = await _context.Specialty.FirstOrDefaultAsync(q => q.Belongs.Name == teacher.CollegeName);

                if (clg != null)
                {
                    var tchr = new Teacher()
                    {
                        Name     = teacher.Name,
                        Sex      = teacher.Sex,
                        Salary   = teacher.Salary,
                        Password = "******",
                        Belongs  = clg
                    };
                    _context.Add(tchr);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            return(View(teacher));
        }
        public async Task <IActionResult> Create([Bind("FirstMidName,HireDate,LastName,OfficeAssignment")] Instructor instructor, string[] selectedCourses)
        {
            // If their selected courses isn't empty then we initialize a new CourseAssignments and insert their data into it.
            if (selectedCourses != null)
            {
                instructor.CourseAssignments = new List <CourseAssignment>();
                foreach (var course in selectedCourses)
                {
                    var courseToAdd = new CourseAssignment {
                        InstructorID = instructor.ID, CourseID = int.Parse(course)
                    };
                    instructor.CourseAssignments.Add(courseToAdd);
                }
            }
            if (ModelState.IsValid)
            {
                _context.Add(instructor);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            PopulateAssignedCourseData(instructor);
            return(View(instructor));
        }
 void ICourseRepository.Save(Course course)
 {
     _db.Add(course);
     _db.SaveChanges();
 }
Example #22
0
 public int Post(ClassRoom classRoom)
 {
     _context.Add(classRoom);
     _context.SaveChanges();
     return(classRoom.Id);
 }
Example #23
0
 public void Save(Enrollment enrollment)
 {
     _db.Add(enrollment);
     _db.SaveChanges();
 }
        public async Task <IActionResult> Create(CreateTransactionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var         walletSender      = _context.Wallet.Find(model.WalletIDSender);
                var         walletRecipient   = _context.Wallet.Find(model.WalletIDRecipient);
                Transaction transactionSender = new Transaction
                {
                    WalletID  = walletSender.WalletID,
                    Type      = model.Type,
                    PlusMinus = '-',
                    Amount    = model.AmountInCurrencySender,
                    AmountInCurrencySender    = model.AmountInCurrencySender,
                    AmountInCurrencyRecipient = model.AmountInCurrencyRecipient,
                    Date        = DateTime.Now,
                    Description = model.Description,
                    Course      = model.Course
                };
                _context.Add(transactionSender);
                await _context.SaveChangesAsync();

                Transaction transactionRecipient = new Transaction
                {
                    WalletID  = walletRecipient.WalletID,
                    Type      = model.Type,
                    PlusMinus = '+',
                    Amount    = model.AmountInCurrencyRecipient,
                    AmountInCurrencySender    = model.AmountInCurrencySender,
                    AmountInCurrencyRecipient = model.AmountInCurrencyRecipient,
                    Date                 = DateTime.Now,
                    Description          = model.Description,
                    Course               = model.Course,
                    RelatedTransactionID = transactionSender.TransactionID
                };
                _context.Add(transactionRecipient);
                await _context.SaveChangesAsync();

                transactionSender.RelatedTransactionID = transactionRecipient.TransactionID;
                _context.Update(transactionSender);
                await _context.SaveChangesAsync();

                walletSender.Balance = walletSender.Balance - model.AmountInCurrencySender;
                _context.Update(walletSender);
                await _context.SaveChangesAsync();

                walletRecipient.Balance = walletRecipient.Balance + (model.AmountInCurrencyRecipient);
                _context.Update(walletRecipient);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            IQueryable <Wallet> wallets = _context.Wallet;

            wallets = wallets.Where(p => p.Delete == false);
            wallets = wallets.Include(p => p.Firm);
            wallets = wallets.Include(p => p.User);
            ViewBag.WalletSender    = new SelectList(wallets, "WalletID", "WalletName", model.WalletIDSender);
            ViewBag.WalletRecipient = new SelectList(wallets, "WalletID", "WalletName", model.WalletIDRecipient);

            ViewBag.Types = new SelectList(types);
            return(View(model));
        }
Example #25
0
        static async Task Main(string[] args)
        {
            SchoolContext context = new SchoolContext();

            #region Phase 1 : 新增與查詢
            #region 新增一筆 person (Last Name: Lee , First Name : Vulcan)
            Person person = new Person()
            {
                LastName  = "Lee",
                FirstName = "Vulcan",
                HireDate  = DateTime.Now
            };
            context.Add(person);
            await context.SaveChangesAsync();

            Console.WriteLine($"Vulcan Lee 已經新增");
            #endregion

            #region 查詢所有名子為 Vulcan 的人員,確認紀錄有新增成功
            var people = await context.Person.Where(x => x.FirstName == "Vulcan").ToListAsync();

            Console.WriteLine($"列出所有名為 Vulcan 的紀錄");
            foreach (var item in people)
            {
                Console.WriteLine($"人員: {item.FirstName} {item.LastName}");
            }
            #endregion
            #endregion

            #region Phase 2 : 修改與查詢
            #region 查詢出剛剛新增紀錄,修改為 Vulcan 為 Avatar
            person = await context.Person.FirstOrDefaultAsync(x => x.FirstName == "Vulcan");

            person.FirstName = "Avatar";
            await context.SaveChangesAsync();

            Console.WriteLine($"Vulcan Lee 已經修改為 Avatar Lee");
            #endregion

            #region 查詢所有名子為 Avatar 的人員,確認紀錄有修改成功
            people = await context.Person.Where(x => x.FirstName == "Avatar").ToListAsync();

            Console.WriteLine($"列出所有名為 Avatar 的紀錄");
            foreach (var item in people)
            {
                Console.WriteLine($"人員: {item.FirstName} {item.LastName}");
            }
            #endregion
            #endregion

            #region Phase 3 : 刪除與查詢
            #region 查詢出剛剛修改紀錄,並且將這筆紀錄刪除
            person = await context.Person.FirstOrDefaultAsync(x => x.FirstName == "Avatar");

            context.Person.Remove(person);
            await context.SaveChangesAsync();

            Console.WriteLine($"Avatar Lee 已經刪除");
            #endregion

            #region 查詢所有名子為 Avatar 的人員,確認紀錄有刪除成功
            people = await context.Person.Where(x => x.FirstName == "Avatar").ToListAsync();

            Console.WriteLine($"列出所有名為 Avatar 的紀錄");
            foreach (var item in people)
            {
                Console.WriteLine($"人員: {item.FirstName} {item.LastName}");
            }
            #endregion
            #endregion
        }
Example #26
0
 public int Post(Course Course)
 {
     _context.Add(Course);
     _context.SaveChanges();
     return(Course.Id);
 }
        public async Task <IActionResult> Create([Bind("Title,Detail,CategoryID,Accessories,Sort,ID")] ContentViewModel contentModel)
        {
            var Category = new List <SelectListItem> ();

            var allCategory = _context.Category.ToList();

            Category.AddRange(Tools.CreateTree(allCategory, -1, 0));
            // add
            for (int i = 0; i < Category.Count; i++)
            {
                if (Category[i].Value == contentModel.CategoryID.ToString())
                {
                    Category[i].Selected = true;
                }
            }
            //add
            ViewBag.Category = Category;

            ViewBag.isSuccess = null;
            if (contentModel.Accessories == null || contentModel.Accessories.Length == 0)
            {
                ModelState.AddModelError("Accessories", "上传SWF格式文件");
            }
            if (!contentModel.Accessories.FileName.EndsWith(".swf"))
            {
                ModelState.AddModelError("Accessories", "上传SWF格式文件");
            }

            if (ModelState.IsValid)
            {
                string FilePath = Path.Combine(_env.WebRootPath, "Upload", "Files");

                if (!Directory.Exists(FilePath))
                {
                    Directory.CreateDirectory(FilePath);
                }
                string fileName = Guid.NewGuid().ToString();
                using (var files = new FileStream(Path.Combine(FilePath, fileName + ".swf"), FileMode.CreateNew))
                {
                    contentModel.Accessories.CopyTo(files);
                }
                ContentModel content = new ContentModel()
                {
                    CategoryID  = contentModel.CategoryID,
                    Title       = contentModel.Title,
                    PublishTime = DateTime.Now,
                    PublisherID = user.AccountID,
                    ModifiedIP  = HttpContext.Connection.RemoteIpAddress.ToString(),
                    Accessories = fileName + ".swf",
                    IsVideo     = false,
                    Sort        = contentModel.Sort
                };

                _context.Add(content);
                await _context.SaveChangesAsync();

                ViewBag.isSuccess = true;
                // add
                ViewBag.InputTitle = "";
                ViewBag.InputSort  = contentModel.Sort + 1;

                return(View(contentModel));
            }
            ViewBag.isSuccess = false;
            return(View(contentModel));
        }
Example #28
0
 //Adicionar un estudiante a la base de datos
 public async Task GrabarEstudiante(Student estudiante)
 {
     _context.Add(estudiante);
     await _context.SaveChangesAsync();
 }
 public IActionResult Post([FromBody] Course course)
 {
     _context.Add(course);
     _context.SaveChanges();
     return(Ok());
 }
 void IStudentRepository.Save(Student student)
 {
     _db.Add(student);
     _db.SaveChanges();
 }