コード例 #1
0
        public async Task <InstructorDto> CreateInstructor([FromBody] InstructorDto instructor)
        {
            // Make sure the name is unique.
            var existing = await mContext.Instructors.SingleOrDefaultAsync(i => i.FirstName == instructor.FirstName &&
                                                                           i.LastName == instructor.LastName);

            if (existing != null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden,
                                                                            $"Instructor named \"{instructor.FirstName} {instructor.LastName}\" already exists"));
            }

            mContext.Instructors.Add(new Instructor()
            {
                FirstName = instructor.FirstName,
                LastName  = instructor.LastName
            });

            // Save the changes to the db asynchronously.
            int records = await mContext.SaveChangesAsync();

            if (records == 1)
            {
                var loaded = await mContext.Instructors.SingleOrDefaultAsync(i => i.FirstName == instructor.FirstName &&
                                                                             i.LastName == instructor.LastName);

                return(InstructorDto.From(loaded));
            }

            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                                                                        "Could not save that instructor"));
        }
コード例 #2
0
        public async Task <InstructorDto> GetInstructor(int id)
        {
            // SingleOrDefaultAsync is an async version of SingleOrDefault.
            var instructor = await mContext.Instructors.SingleOrDefaultAsync(i => i.Id == id);

            if (instructor != null)
            {
                return(InstructorDto.From(instructor));
            }
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                                        $"Instructor id \"{instructor.Id}\" not found"));
        }