iT邦幫忙

2023 iThome 鐵人賽

DAY 21
0
Cloud Native

.NET雲端魔法尊者之路系列 第 21

2023-鐵人賽.NET雲端魔法尊者之路 Day21 .NET篇 LINQ應用

  • 分享至 

  • xImage
  •  

當談到在.NET中使用LINQ(Language-Integrated Query)時,我們談論的是一種強大的語言特性,它允許我們以類似SQL的方式來查詢和操作數據集合,無論是在記憶中的集合、數組、數據庫或XML文件中。LINQ通常用於.NET框架中的C#或VB.NET等語言。

範例

using System;
using System.Collections.Generic;
using System.Linq;
using api_demo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// GET: api/users
[Route("api/users")]
[ApiController]
public class UserController : ControllerBase
{
    private readonly DemoContext _context;

    public UserController(DemoContext context)
    {
        _context = context;
    }
    [HttpGet]
    public ActionResult<IEnumerable<Test>> GetUsers()
    {
        var users = _context.Test.ToList();
        var response = new { result = 0, msg = "OK", data = users };
        return Ok(response);
    }

    // GET: api/users/5
    [HttpGet("{id}")]
    public ActionResult<Test> GetUser(int id)
    {
        var user = _context.Test.FirstOrDefault(u => u.user_id == id);

        if (user == null)
        {
            var notFoundResponse = new { result = -1, msg = "User not found" };
            return NotFound(notFoundResponse);
        }

        var response = new { result = 0, msg = "OK", data = user };
        return Ok(response);
    }

    // POST: api/users
    [HttpPost]
    public ActionResult<Test> CreateUser(Test user)
    {
        _context.Test.Add(user);
        _context.SaveChanges();

        var response = new { result = 0, msg = "OK", data = user };
        return CreatedAtAction(nameof(GetUser), new { id = user.user_id }, response);
    }

    // PUT: api/users/5
    [HttpPut("{id}")]
    public IActionResult UpdateUser(int id, Test user)
    {
        if (id != user.user_id)
        {
            var badRequestResponse = new { result = -1, msg = "Invalid request" };
            return BadRequest(badRequestResponse);
        }

        _context.Entry(user).State = EntityState.Modified;

        try
        {
            _context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!_context.Test.Any(u => u.user_id == id))
            {
                var notFoundResponse = new { result = -1, msg = "User not found" };
                return NotFound(notFoundResponse);
            }
            else
            {
                throw;
            }
        }

        var response = new { result = 0, msg = "OK" };
        return Ok(response);
    }

    // DELETE: api/users/5
    [HttpDelete("{id}")]
    public IActionResult DeleteUser(int id)
    {
        var user = _context.Test.FirstOrDefault(u => u.user_id == id);

        if (user == null)
        {
            var notFoundResponse = new { result = -1, msg = "User not found" };
            return NotFound(notFoundResponse);
        }

        _context.Test.Remove(user);
        _context.SaveChanges();

        var response = new { result = 0, msg = "OK" };
        return Ok(response);
    }
}

以下是一個.NET API的範例,介紹了如何使用它來執行刪除、增加、更新和搜索操作。

結語

那今天就到這裡囉 掰掰~

參考資料

https://learn.microsoft.com/zh-tw/archive/msdn-magazine/2013/january/asp-net-building-hypermedia-web-apis-with-asp-net-web-api


上一篇
2023-鐵人賽.NET雲端魔法尊者之路 Day20 .NET篇 SQL Server 創建表
下一篇
2023-鐵人賽.NET雲端魔法尊者之路 Day22 雲端篇 DevOps
系列文
.NET雲端魔法尊者之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言