ASP.NET Core .NET 5 打造RESTful API入門教學(7) - 修改資料PUT

Leave a Comment
Find更新用法
        [HttpPut("{id}")]
        public void Put(Guid id, [FromBody] Todo value)
        {
            var update = _todoContext.Todos.Find(id);
            if (update != null)
            {
                update.Name = value.Name;
                update.Orders = value.Orders;
                update.Enable = value.Enable;
                update.UpdateTime = DateTime.Now;
                _todoContext.SaveChanges();
            }
        }
用update物件更新用法
        [HttpPut("{id}")]
        public void Put(Guid id, [FromBody] Todo value)
        {
            value.TodoId = id;
            value.UpdateTime = DateTime.Now;

            var update = _todoContext.Todos.Update(value);

            update.Property("InsertTime").IsModified = false;

            _todoContext.SaveChanges();
        }
SingleOrDefault更新用法
        [HttpPut("{id}")]
        public void Put(Guid id, [FromBody] Todo value)
        {
            var update = (from a in _todoContext.Todos
                          where a.TodoId.Equals(id)
                          select a).SingleOrDefault();

            if (update != null)
            {
                update.Name = value.Name;
                update.Orders = value.Orders;
                update.Enable = value.Enable;
                update.UpdateTime = value.UpdateTime;
                _todoContext.SaveChanges();
            }
            else
            {
                var insert = new Todo
                {
                    Name = value.Name,
                    Orders = value.Orders,
                    Enable = value.Enable
                };
                _todoContext.Todos.Add(insert);
                _todoContext.SaveChanges();
            }
        }

0 意見:

張貼留言

技術提供:Blogger.