netcore使用EFcore(第一个实例)
说明:搭建netcore 使用efcore入门教程,跟着这个教程,傻瓜都可以成功!o(∩_∩)o哈哈~,咱们开始吧;
首先介绍下环境:
vs2017,
netcore2.2,
entityframework6
测试场景:mysql,sqlserver
一、创建netcore模板项目
这个就不用多说了,创建完成看下版本:
二、引用ef core
有的博主写的这样引用:install-package microsoft.entityframeworkcore.sqlite –pre
但是,遗憾的是,报错了:
然后我自己引用了以包,ok
为了方便复制,我直接复制出来:
1.microsoft.entityframeworkcore
2.install-package microsoft.entityframeworkcore.sqlite
3.install-package microsoft.entityframeworkcore.design
4.install-package microsoft.entityframeworkcore.tools
项目结构如下:
三、创新测试的实体类
我这边创建了一个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; } }
四、创建一个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; }
}
五、创建数据库初始化和连接
为了方便测试,将数据库连接配置放在了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();//数据库不存在的话,会自动创建
六、打开对应文件目录,执行
打开文件夹的命令行,
输入
dotnet ef migrations add myfirstmigration
dotnet ef database update
这样我们就创建好了数据库。更多命令请 dotnet ef -h
看一下我们的数据库数据:
运行完成之后,我们会发现,我们会多一个migrations文件夹
里面的内容是什么呢,大家可以打开看看,下面是我的部分截图:
可以看到,这些都是我们之前创建实体时的一些属性,如果是第一次尝试的朋友也没有必要设置这么多。
七、测试效果
简单写了个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的东西,如有问题,欢迎一起讨论。
感谢以下文章提供的启发:
参考博客:
参考文档:
上一篇: 碎尸案有没有自杀的可能
下一篇: C语言中动态数组的实现