說明:搭建netcore 使用efcore入門教程,跟着這個教程,傻瓜均可以成功!O(∩_∩)O哈哈~,我們開始吧;html
首先介紹下環境:sql
vs2017,數據庫
netcore2.2,json
EntityFramework6app
測試場景:Mysql,SqlServerpost
1、建立netcore模板項目學習
這個就不用多說了,建立完成看下版本:測試
2、引用EF Coreui
有的博主寫的這樣引用:Install-Package Microsoft.EntityFrameworkCore.Sqlite –Prespa
可是,遺憾的是,報錯了:
而後我本身引用了以包,OK
爲了方便複製,我直接複製出來:
1.Microsoft.EntityFrameworkCore
2.Install-Package Microsoft.EntityFrameworkCore.Sqlite
3.Install-Package Microsoft.EntityFrameworkCore.Design
4.Install-Package Microsoft.EntityFrameworkCore.Tools
項目結構以下:
3、創新測試的實體類
我這邊建立了一個DBModel文件夾,而後分別建立了三個類:
OrderInfo.cs,
Passenger.cs,
Address.cs
爲何要建立這麼幾個呢:由於後續會設計到表之間關聯關係,主鍵,外鍵,引用等等,固然,本文主要是入門,後面的文章會詳細講解;
(PS:關係:一個OrderInfo有一個Passenger和一個Address,一個Passenger又能夠有多個OrderInfo和一個Address);
強調:須要引用MySql.Data.EntityFrameworkCore
OrderInfo.cs
[MySqlCharset("utf8mb4")] //字符集,須要引用MySql.Data.EntityFrameworkCore [MySqlCollation("utf8mb4_general_ci")] //排序規則 [Table("orderinfo", Schema = "manager")] public class OrderInfo { [JsonProperty("id")] [Required] [Column("id", TypeName = "int(11)")] public int Id { get; set; } /// <summary> /// 訂單Id /// </summary> [JsonProperty("order_id")] [Required] [Column("order_id", TypeName = "int(11)")] public int OrderId { get; set; } [JsonProperty("passengerid")] [Column("passenger_id",TypeName ="int(11)")] public int PassengerId { get; set; } [JsonProperty("addressid")] [Column("address_id", TypeName = "int(11)")] public int AddressId { get; set; } /// <summary> /// 訂單價格 /// </summary> [StringLength(maximumLength: 100)] [Column("price")] public string Price { get; set; } /// <summary> /// 訂單客人信息 /// </summary> [ForeignKey("PassengerId")] public Passenger OrderForPassenger { get; set; } ///// <summary> ///// 訂單地址信息 ///// </summary> //[InverseProperty("OrderInfos")] //public Address OrderForAddress { get; set; }
Passenger.cs
[MySqlCharset("utf8mb4")] //字符集,須要引用MySql.Data.EntityFrameworkCore [MySqlCollation("utf8mb4_general_ci")] //排序規則 [Table("passenger", Schema = "manager")] public class Passenger { [JsonProperty("id")] [Column("id", TypeName = "int(10)")] public int Id { get; set; } [JsonProperty("passenger_id")] [Column("passengerid",TypeName ="int(11)")] public int PassengerId { get; set; } [JsonProperty("passengername")] public string PassengerName { get; set; } [InverseProperty("OrderForPassenger")] public List<OrderInfo> OrderInfos { get; set; } //[InverseProperty("Passengers")] //public Address PssengerForAddress { get; set; } }
Address.cs
[MySqlCharset("utf8mb4")] //字符集,須要引用MySql.Data.EntityFrameworkCore [MySqlCollation("utf8mb4_general_ci")] //排序規則 [Table("address", Schema = "manager")] public class Address { [JsonProperty("id")] [Required] public int Id { get; set; } [JsonProperty("province")] [StringLength(maximumLength: 256)] public string Province { get; set; } [JsonProperty("city")] [StringLength(maximumLength: 256)] public string City { get; set; } [JsonProperty("area")] [StringLength(maximumLength: 256)] public string Area { get; set; } [JsonProperty("street")] [StringLength(maximumLength:256)] public string Street { get; set; } }
4、建立一個DataDBContext.cs類,代碼以下
public class DataDBContext:DbContext { public DataDBContext(DbContextOptions<DataDBContext> options) : base(options) { } /// <summary> /// 訂單 /// </summary> public DbSet<OrderInfo> OrderInfos { get; set; } /// <summary> /// 乘客 /// </summary> public DbSet<Passenger> Passengers { get; set; } /// <summary> /// 地址 /// </summary> public DbSet<Address> Addresses { get; set; } }
5、建立數據庫初始化和鏈接
爲了方便測試,將數據庫鏈接配置放在了appsettings.json文件中了。配置文件內容以下:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionSetting": { "UserConnectionString": "server=localhost;userid=root;pwd=123456;port=3306;database=manager", "ReadConnectionString": "server=localhost;userid=root;pwd=123456;port=3306;database=manager", "DbType": 0 //數據庫類型 } }
在StartUp.cs中註冊鏈接:
services.AddDbContext<DataDBContext>(optionsBuilder => { var dataAppSetting = Configuration.GetSection("ConnectionSetting").Get<ConnectionSetting>(); if (dataAppSetting == null) { throw new Exception("未配置數據庫鏈接"); } switch (dataAppSetting.DbType) { case 1: //server鏈接,EnableRetryOnFailure表示失敗支持重試; optionsBuilder.UseSqlServer(dataAppSetting.UserConnectionString, option => option.EnableRetryOnFailure()); break; default: optionsBuilder.UseMySQL(dataAppSetting.UserConnectionString); break; } });
這裏可能有朋友會問一下,萬一數據庫沒有建立怎麼辦?
因此,這裏Configure方法加一下內容
context.Database.EnsureCreated();//數據庫不存在的話,會自動建立
6、打開對應文件目錄,執行
打開文件夾的命令行,
輸入
dotnet ef migrations add MyFirstMigration
dotnet ef database update
這樣咱們就建立好了數據庫。更多命令請 dotnet ef -h
看一下咱們的數據庫數據:
運行完成以後,咱們會發現,咱們會多一個Migrations文件夾
裏面的內容是什麼呢,你們能夠打開看看,下面是個人部分截圖:
能夠看到,這些都是咱們以前建立實體時的一些屬性,若是是第一次嘗試的朋友也沒有必要設置這麼多。
7、測試效果
簡單寫了個demo測試效果
話很少說,直接上代碼:
Index.cshtml
@model IEnumerable<EfCoreDemo.DbModel.Address> @{ ViewBag.Title = "地址"; } <table class="table"> <tr> <th>Id</th> <th>省</th> <th>市</th> <th>區</th> <th>街道詳細地址</th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Id) </td> <td> @Html.DisplayFor(modelItem => item.Province) </td> <td> @Html.DisplayFor(modelItem => item.City) </td> <td> @Html.DisplayFor(modelItem => item.Area) </td> <td> @Html.DisplayFor(modelItem => item.Street) </td> </tr> } </table>
AddAddress.cshtml
@model EfCoreDemo.DbModel.Address @{ ViewData["Title"] = "Address"; } <form asp-controller="Address" asp-action="AddAddress" method="post"> <div class="form-group"> <label asp-for="Province" class="col-md-2 control-label">省:</label> <div class="col-md-10"> <input class="form-control" asp-for="Province" /> <span asp-validation-for="Province" class="text-danger"></span> </div> <label asp-for="City" class="col-md-2 control-label">市:</label> <div class="col-md-10"> <input class="form-control" asp-for="City" /> <span asp-validation-for="City" class="text-danger"></span> </div> <label asp-for="Area" class="col-md-2 control-label">區:</label> <div class="col-md-10"> <input class="form-control" asp-for="Area" /> <span asp-validation-for="Area" class="text-danger"></span> </div> <label asp-for="Street" class="col-md-2 control-label">街道門牌號:</label> <div class="col-md-10"> <input class="form-control" asp-for="Street" /> <span asp-validation-for="Street" class="text-danger"></span> </div> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="保存" class="btn btn-success" /> </div> </div> </form>
AddressController.cs
public class AddressController : Controller
{
private DataDBContext _context;
public AddressController(DataDBContext context) {
_context = context;
}
public IActionResult Index()
{
return View(_context.Addresses.ToList());
}
public IActionResult AddAddress() {
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddAddress(Address address) {
if (ModelState.IsValid) {
_context.Addresses.Add(address);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(address);
}
運行效果:
至此,初級版本搭建成功,且運行成功;
後記:本文主要是記錄一下netcore怎麼搭建efcore,只屬於基礎,本身學習的過程當中也方便跟你們一塊兒探討,後續會繼續更新更多的efcore的東西,若有問題,歡迎一塊兒討論。
感謝如下文章提供的啓發:
參考博客:http://www.javashuo.com/article/p-tluwlcez-eo.html
參考文檔:https://docs.microsoft.com/zh-cn/ef/core/get-started/netcore/new-db-sqlite