示例#1
0
        // POST api/Students
        public HttpResponseMessage PostStudent(StudentModel studentModel)
        {
            if (studentModel == null)
            {
                var errResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The supported student model cannot be null");
                throw new HttpResponseException(errResponse);
            }

            if (studentModel.SchoolId == 0)
            {
                var errResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The school Id is not correct");
                throw new HttpResponseException(errResponse);
            }

            DbSchoolRepository schoolRepository = this.allRepositories.GetSchoolRepository();

            Student student = new Student()
            {
                FirstName = studentModel.FirstName,
                LastName  = studentModel.LastName,
                Age       = studentModel.Age,
                Grade     = studentModel.Grade,
                School    = schoolRepository.Get(studentModel.SchoolId)
            };

            DbStudentsRepository studentRepository = this.allRepositories.GetStudentsRepository();

            studentRepository.Add(student);

            StudentModel createdStudentModel = new StudentModel()
            {
                Id        = student.Id,
                FirstName = student.FirstName,
                LastName  = student.LastName,
                Age       = student.Age,
                Grade     = student.Grade,
                SchoolId  = student.School.Id
            };

            var response     = Request.CreateResponse <StudentModel>(HttpStatusCode.Created, createdStudentModel);
            var resourceLink = Url.Link("DefaultApi", new { id = createdStudentModel.Id });

            response.Headers.Location = new Uri(resourceLink);
            return(response);
        }
示例#2
0
        // GET api/Students/5
        public SchoolDetails GetStudent(int id)
        {
            DbSchoolRepository schoolRepository = this.allRepositories.GetSchoolRepository();

            var school        = schoolRepository.Get(id);
            var schoolDetails = new SchoolDetails()
            {
                Id       = school.Id,
                Name     = school.Name,
                Location = school.Location,
                Students = (from student in school.Students
                            select new StudentModel()
                {
                    Id = student.Id,
                    FirstName = student.FirstName,
                    LastName = student.LastName,
                    Age = student.Age,
                    Grade = student.Grade
                }).ToList()
            };

            return(schoolDetails);
        }