注意:本文使用ASP.NET Core版本为1.x
首先新建一个项目 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;
}
再修改Startup.cs文件的ConfigureServices方法
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>
再修改一下项目的属性,然后运行即可