.net6 web api uses EF Core to automatically generate tables according to the model class


1. Install the nuget package Microsoft.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql of EF Core and mysql database
insert image description here
2. Create the models folder and create entity classes under the folder
insert image description here

  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
insert image description here

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;"
  }

insert image description here
5. Implement dependency injection in the Program.cs class
insert image description here
6. Use in the controller, add a controller named UsersController
insert image description here

 [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
insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44442366/article/details/129407601