1. 创建新项目-ASP.NET Core Web 应用程序
2.
3. 右键项目-管理 NuGet 程序包(N)...
4. 搜索 Pomelo.EntityFrameworkCore.MySql 安装
5. 在appsettings.json文件添加 数据库连接字符串
"AllowedHosts": "*","ConnectionStrings": {"MysqlConnection": "Data Source=192.168.199.999;Database=gf;User ID=root;Password=123456;pooling=true;port=3306;sslmode=none;CharSet=utf8;"}
6. 添加一个Model
[Table("flash_map2")] //特性,标记为mySql数据库中的具体表名
public class MapFlash
{
[Key] //特性,标记为主键
public int id_no { get; set; }
public string flash_name { get; set; }
}
7. 添加MysqlDbContext类,用来连接数据库
public classMysqlDbContext: DbContext
{public MysqlDbContext(DbContextOptions options) : base(options)
{
}public DbSet flash_map23 { get; set; }
}
8. 在Startup类的ConfigureServices的方法中注入一下
public voidConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMvc();
services.AddScoped();var connection = Configuration.GetConnectionString("MysqlConnection");
services.AddDbContext(options =>options.UseMySql(connection));
}
9. 到这一步就完成全部配置了,然后可以使用了
10. 创建一个控制器,使用一下
public classTestController : Controller
{privateDbContext dbContext;publicTestController(DbContext _dbContext)
{this.dbContext =_dbContext;
}publicIActionResult Index()
{var data = dbContext.Set().Find(37);
ViewData["aa"] =data.flash_name;returnView();
}
}
11. 添加视图-右键上面代码中的 Index 添加视图
@{
ViewData["Title"] = "Index";
}
Index
12. 运行查看结果
13. 完成
14. 如有其他疑问请在评论区留言