ASP.NET CORE WebAPI Entity Framework 기반 CRUD 추가 검색 및 삭제

2099 단어 WebAPI
WebAPI Entity Framework 기반 Post Get Put Delete
Get 정보 조회
       //Get:api/todoapi
        [HttpGet]
        public async Task>> GetTodoItems()
        {
            return await _context.TodoItem.ToListAsync();
        }

        //Get:api/todoapi/id
        [HttpGet("{id}")]
        public async Task> GetTodoItem(long id)
        {
            //FindAsync   id  
            var todoItem = await _context.TodoItem.FindAsync(id);
            if (todoItem == null)
            {
                //  404
                return NotFound();
            }
            //     json  
            return todoItem;
        }

Post 정보 작성
        //Post:api/todoapi
        [HttpPost]
        public async Task> PostTodoItem(TodoItem item)
        {
            _context.TodoItem.Add(item);
            await _context.SaveChangesAsync();
            //CreatedAtAction(actionName,routeValues,value).
            return CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item);
        }

Put 정보 수정
        //Put:api/todoapi/id
        [HttpPut("{id}")]
        public async Task PutTodoItem(long id,TodoItem item)
        {
            if (id != item.Id)
            {
                return BadRequest();
            }
            _context.Entry(item).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return NoContent();
        }

삭제 정보 삭제
 //Delete:api/todoapi/id
        [HttpDelete("{id}")]
        public async Task DeleteTodoItem(long id)
        {
            var todoItem = await _context.TodoItem.FindAsync(id);

            if (todoItem == null)
            {
                return NotFound();
            }
            _context.TodoItem.Remove(todoItem);
            await _context.SaveChangesAsync();

            return NoContent();
        }

좋은 웹페이지 즐겨찾기