1. 創建新項目-ASP.NET Core Web 應用程式 2. 3. 右鍵項目-管理 NuGet 程式包(N)... 4. 搜索 Pomelo.EntityFrameworkCore.MySql 安裝 5. 在appsettings.json文件添加 資料庫連接字元串 "AllowedHosts ...
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 class MysqlDbContext: DbContext { public MysqlDbContext(DbContextOptions<MysqlDbContext> options) : base(options) { } public DbSet<MapFlash> flash_map23 { get; set; } }
8. 在Startup類的ConfigureServices的方法中註入一下
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddMvc(); services.AddScoped<DbContext, MysqlDbContext>(); var connection = Configuration.GetConnectionString("MysqlConnection"); services.AddDbContext<MysqlDbContext>(options => options.UseMySql(connection)); }
9. 到這一步就完成全部配置了,然後可以使用了
10. 創建一個控制器,使用一下
public class TestController : Controller { private DbContext dbContext; public TestController(DbContext _dbContext) { this.dbContext = _dbContext; } public IActionResult Index() { var data = dbContext.Set<MapFlash>().Find(37); ViewData["aa"] = data.flash_name; return View(); } }
11. 添加視圖-右鍵上面代碼中的 Index 添加視圖
@{ ViewData["Title"] = "Index"; } <h1>Index</h1> <div> @ViewData["aa"] </div>
12. 運行查看結果
13. 完成
14. 如有其他疑問請在評論區留言