基於EF Core + MySQL的基本增刪改查,範例是基於.NET6 + EF Core + MySQL 建立實體和資料庫、EFCore 資料遷移專案基礎上的內容增加。同時也是對基於Canal實現MySQL 8.0 資料庫資料同步專案的驗證。
Controllers---->新增---->控制器,選擇api---->包含讀寫操作的API控制器。
將上下文類注入到UsersController中,ASP.NET Core 支援依賴關係注入 (DI) 軟體設計模式,這是一種在類及其依賴關係之間實現控制反轉 (IoC) 的技術。有三種具體實現方式,我們這裡用到的是建構函式注入,關於這塊的內容,以後我們也可以專門出一期。直接上程式碼。
private readonly MyDataBaseContext_mian _dbmain;
private readonly MyDataBaseContext_from _dbfrom;
public UsersController(MyDataBaseContext_mian dbmain, MyDataBaseContext_from dbfrom)
{
_dbmain = dbmain;
_dbfrom = dbfrom;
}
一下內容是UsersController的完整內容
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using test.Models;
using test.MyDataBaseContext;
namespace test.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UsersController : Controller
{
private readonly MyDataBaseContext_mian _dbmain;
private readonly MyDataBaseContext_from _dbfrom;
public UsersController(MyDataBaseContext_mian dbmain, MyDataBaseContext_from dbfrom)
{
_dbmain = dbmain;
_dbfrom = dbfrom;
}
[HttpGet]
// GET: UsersController
public IEnumerable<User> Index()
{
return _dbfrom.Users.ToList();
}
[HttpGet("{id}")]
// GET: UsersController/Details/5
public async Task<IActionResult> Details(int? id)
{
return CreatedAtAction(nameof(Index), await _dbfrom.Users.AsNoTracking().FirstOrDefaultAsync(m => m.UserId == id));
}
// POST: UsersController/Create
[HttpPost]
public async Task<IActionResult> Create(User user)
{
_dbmain.Users.Add(user);
await _dbmain.SaveChangesAsync();
return CreatedAtAction(nameof(Index), new { id = user.UserId }, user);
}
// POST: UsersController/Edit/5
[HttpPut("{id}")]
public async Task<bool> Edit(int? id, [FromBody] User user)
{
_dbmain.Set<User>().Update(user);
return await _dbmain.SaveChangesAsync() > 0;
}
// POST: UsersController/Delete/5
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
User user = new User();
user = await _dbmain.Users.FindAsync(id);
if (user == null)
{
return RedirectToAction(nameof(Index));
}
try
{
_dbmain.Users.Remove(user);
await _dbmain.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
return RedirectToAction(nameof(Index), new { id = id, saveChangesError = true });
}
}
}
}
注:我對方法進行的改造,採用官網提供的新寫法,有興趣的小夥伴可以看看官網。
到此,EFCore的增刪改查就完事了。有不懂的小夥伴可以把問題打在評論區,我來為大家解答。