標籤:into class values 字元 log 開源 setting tle com
既然NetCore開源,那麼也使用開源的MySQL的資料庫呢?當然NetCore不止單單配MSSQL資料庫而已。今天我來講解NetCore怎麼使用MySQL進行開發。
首先建立一個NetCore項目
然後寫兩個類放在Model裡面
public class Lexan { private LexanContext lexanContext; public string Name { get; set; } public int Sex { get; set; } public int Age { get; set; } }
public class LexanContext { public string ConnectionString { get; set; } public LexanContext(string connectionString) { ConnectionString = connectionString; } private MySqlConnection GetConnection() { return new MySqlConnection(ConnectionString); } public List<Lexan> GetLexan() { List<Lexan> list = new List<Lexan>(); using (MySqlConnection connection=GetConnection()) { connection.Open(); MySqlCommand command = new MySqlCommand("select * from Lexan",connection); using (MySqlDataReader reader=command.ExecuteReader()) { while (reader.Read()) { list.Add(new Lexan() { Name=reader.GetString("Name"), Sex=reader.GetInt32("Sex"), Age=reader.GetInt32("Age") }); } } } return list; } }
然後在NuGet庫裡安裝個外掛程式才能完成串連MySQL
然後添加一個控制器
public IActionResult Index() { LexanContext wordcontext = HttpContext.RequestServices.GetService(typeof(AspNetCoreUseMySQL.Model.LexanContext)) as LexanContext; return View(wordcontext.GetLexan()); //return View(); }
然後添加一個MVC 視圖
然後添加如下代碼,你也可以根據自己的情況稍作修改
@model IEnumerable<AspNetCoreUseMySQL.Model.Lexan>@{ ViewBag.Title = "Lexan";}<h1>Lexan</h1><table class="table"> <tr> <th>名字</th> <th>性別</th> <th>年齡</th> </tr> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelitem => item.Name)</td> <td>@Html.DisplayFor(modelitem => item.Sex)</td> <td>@Html.DisplayFor(modelitem => item.Age)</td> </tr> }</table>
然後修改Startup類,添加如下代碼
services.Add(new ServiceDescriptor(typeof(LexanContext), new LexanContext(Configuration.GetConnectionString("DefaultConnection"))));
然後往appsettings.json裡寫連接字串,這裡注意一下,每個人的密碼都不一樣,你也要稍作修改,不然會出現串連出錯
我們來建立一個資料庫,並建立表,然後往裡面寫一條資料
create database AspNetCoreUseMySql; use AspNetCoreUseMySql; show tables; create table Lexan (name varchar(20),sex char(1),Age char(5)); describe Lexan; insert into Lexan values(‘Lexan‘,‘0‘,‘22‘); select * from Lexan;
全部工作完成了,我們來運行看看效果
最後博主在這裡說一下,凡是本博主的博文,麻煩添加原文地址,謝謝!所有部落格文章都來自Lexan的部落格,你也可以關注博主的博文地址http://www.cnblogs.com/R00R/
AspNetCore使用MySQL