首先新建一個項目 Asp.NetCoreConnectorMySQL
通過簡單的修改運行如下
接下來安裝NuGet安裝MySQL的庫
查看MySQL裏面自帶的數據庫
我們來修改json文件(appsettings.json)建立MySQL的連接串
新建一個類(這裏我的類名是Lexan,你的不一定是Lexan)
private WorldContext worldcontext { get; set; }
public string LexanCode { get; set; }
public string LexanName { get; set; }
public string LexanContinent { get; set; }
public string LexanRegion { get; set; }
在新建一個操作數據庫的類(WorldContext)
public string ConnectionString { get; set; }
public WorldContext(string connectionString)
{
this.ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<Country> GetAllCountry()
{
List<Country> list = new List<Country>();
using (MySqlConnection msconnection=GetConnection())
{
msconnection.Open();
MySqlCommand mscommand = new MySqlCommand("select * from country",msconnection);
using (MySqlDataReader reader=mscommand.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Country()
{
Code = reader.GetString("Code"),
Name=reader.GetString("Name"),
Continent=reader.GetString("Continent"),
Region=reader.GetString("Region")
});
}
}
}
return list;
}
services.Add(new ServiceDescriptor(typeof(WorldContext),new WorldContext(Configuration.GetConnectionString("DefaultConnection"))));
新建一個控制器類
WorldContext context = HttpContext.RequestServices.GetService(typeof(Asp.NetCoreConnectorMySQL.Model.WorldContext)) as WorldContext
return View(context.GetAllCountrys())
添加一個MVC視圖頁
@model IEnumerable<AspNetCoreConnectionMySQL.Model.Country>
@{
ViewBag.Title = "Lexan";
}
<h1>國家</h1>
<table class="table">
<tr>
<th>國家代碼</th>
<th>國家名</th>
<th>陸地</th>
<th>區域</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelitem=>item.Code)</td>
<td>@Html.DisplayFor(modelitem=>item.Name)</td>
<td>@Html.DisplayFor(modelitem=>item.Continent)</td>
<td>@Html.DisplayFor(modelitem=>item.Region)</td>
</tr>
}
</table>
再修改一下項目的屬性,然後運行即可