1. Install the nuget package Microsoft.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql of EF Core and mysql database
2. Create the models folder and create entity classes under the folder
public class Users
{
public int Id {
get; set; }
[Column(TypeName = "varchar(200)"), Required]
public string Name {
get; set; }
[Column(TypeName = "varchar(200)")]
public string Email {
get; set; }
[Column(TypeName = "varchar(200)")]
public string age {
get; set; }
}
3. Create a database context operation class MyDbContext to inherit DbContext
namespace EfCore
{
public class MyDbContext: DbContext
{
//添加Users实体类
public DbSet<Users> Users {
get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//modelBuilder.Entity<MyModel>()
// .HasKey(x => x.Id);
// modelBuilder.Entity<Users>()
// .Property(e => e.Email)
// .IsRequired()
// .HasMaxLength(50);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
}
//构造函数
public MyDbContext(DbContextOptions<MyDbContext> option) : base(option)
{
// 如果数据库表不存在则创建
Database.EnsureCreated();
// 执行自动迁移以将数据库与实体类定义同步
Database.Migrate();
}
}
}
4. Add a database connection string to the appsettings.json file
"ConnectionStrings": {
"DbConnectionString": " Data Source=localhost;Database=efcore;AllowLoadLocalInfile=true;User ID=root;Password=root;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;port=3306;sslmode=none;"
}
5. Implement dependency injection in the Program.cs class
6. Use in the controller, add a controller named UsersController
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly MyDbContext _context;
public UsersController(MyDbContext context)
{
_context = context;
}
[HttpGet("user")]
public ActionResult<IEnumerable<Users>> Get()
{
return _context.Users.ToList();
}
}
7. Start the project and call the api interface, and find that the database table is successfully created to realize automatic migration