基于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的增删改查就完事了。有不懂的小伙伴可以把问题打在评论区,我来为大家解答。