1. 添加如下NuGet包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Sqlite
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
2.添加模型类,比如Users
public class Users
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Age { get; set; }
public string? Phone { get; set; }
}
3. 添加数据库上下文类
public class MyDBContext : DbContext
{
public MyDBContext(DbContextOptions options) : base(options)
{
}
public DbSet<Users> Users { get; set; }
}
4. 在 appsettings.json 文件数据库连接字符串
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MyContext": "Filename=Data\\MY.DB"
}
}
5. 在Program.cs 添加如下代码启用数据库上下文
string connecttext = Configuration.GetConnectionString("MyContext");
builder.Services.AddDbContext<MyContext>(options=>options.UseSqlite(connecttext));
6. 在VS NuGet 包管理器->程序包管理器控制台 输入如下命令
Add-Migration InitialCreate
7. 上述命令执行成功后输入如下命令
Update-Database
8. 在 Controller 目录,右键点击 添加 -- 新建基架的项目,点击 视图使用 Entity Framework 的 MVC 控制器,
模型类 选择 Users([项目名称].Models)
数据库上下文选择 MyContext ([项目名称].Models)
点击 添加
9. 自动生成的控制器和页面可以供参考或这直接修改使用