尝试.Net Core—使用.Net Core + Entity FrameWork Core构建WebAPI(一)
想尝试.Net Core很久了,一直没有时间,今天回家,抛开一切,先搭建一个.Net Core的Demo出来玩玩。
废话少说,咱直奔主题:
一、开发环境
VS2015 Update3
Microsoft .NET Core Tools(Preview 2)
本来想用VS Code来着,但是本着最简单原理,这里先用VS 2015,我又不是受虐狂,为啥有好用的工具摆在这里不用呢,你说是吧?
二、新建解决方案
与ASP.NET时代没有什么区别,直接新建一个解决方案,在左边选择.NET Core, 然后项目模版选择ASP.NET Core Web Application(.NET Core) 如下图。

然后填写解决方案名称和项目名称,并选择保存路径(这和以前完全一样)。然后到了第二步,选择Web API模版,身份验证方式选择无身份验证(这里只是Demo,身份验证咱就不折腾了吧,毕竟这个往往非常复杂)。并且去掉他默认打上的Host In Cloud的勾(如果你有Azure的服务器,可以勾上)。

到此,项目就创建完毕了。你可以直接点上面的运行,把项目跑起来,会直接打开一个默认的API(ValueContrller)。
这里我又创建了一个.NET Core的类库项目,用来作为数据库访问层,名称为DataAccess,这个跟原来.NET 时代的类库项目没有什么区别,只是需要建成.NET Core类库。
新建完成的解决方案结构如下:

三、开始Coding
这里我以获取本地某个数据库中Address表的前10条记录为例。
1.新建一个实体类Address
使其字段与数据库一一对应,记得不要忘了设置主键(Id)上面的[Key]特性标签。
public class Address
{
[Key]
public Guid Id { get; set; }
public string OpenId { get; set; }
/// <summary>
/// 收件人姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 详细收货地址(目前仅限与榆林学院)
/// </summary>
public string DetailAddress { get; set; }
/// <summary>
/// 联系电话
/// </summary>
public string Tel { get; set; }
/// <summary>
/// 是否默认地址
/// </summary>
public bool IsDefault { get; set; }
}
2.添加引用
通过Nuget为项目DataAccess和WebTest引用Microsoft.EntityFrameworkCore和Microsoft.EntityFrameworkCore.SqlServer
3.新建EF Core上下文(EFDbContext)
public class EFDbContext: DbContext
{
public EFDbContext(DbContextOptions<EFDbContext> options):base(options)
{ }
public DbSet<Address> Address { get; set; }
}
4.配置EFDbContext的启动项
在Web项目的StartUp类中,找到ConfigureServices方法,新增EF的启动项,代码如下面的第一句:
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer().AddDbContext<EFDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc();
}
这里面有两个地方需要说明:
- 这个方法会在项目启动的时候被调用,并且EFDbContext会被注册到ASP.NET Core自带的IOC中,以后就可以在别的地方直接注入EFDbContext了(下面会用到)。
- Configuration.GetConnectionString("SqlServer")这是去读系统的配置,系统配置都在appsettings.json文件中,需要手动添加一下配置,添加完成后类似于:
{
"ConnectionStrings": {
"SqlServer": "Data Source=localhost;Initial Catalog=database-name;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=password"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
5.WebAPI Controller
首先,上代码~
[Route("api/address")]
public class AddressController : Controller
{
private EFDbContext _context;
public AddressController(EFDbContext context)
{
_context = context;
}
[HttpGet,Route("getall")]
public IList<Address> GetAll()
{
var list= _context.Address.Take().ToList();
return list;
}
}
下面来听我慢慢道来。
- 首先: [Route("api/address")]这个是用来定义API的公共部分,这个如果你有过WebAPI的开发经验,这个非常容易看懂,在WebAPI中,这个会被写成[RoutePreFix("api/address")]
- 其次,我们看到EFDbContext是通过构造函数被注入了,这个就会用到我们在上面StartUp类中所配置的信息。
- 接下来,方法GetAll上面的特性标签[HttpGet]定义了该API的请求谓词,Route("getall")定义了该API的地址,最终,这个地址和在Controller上面的Route会共同来决定这个API的地址,本例中这个GetAll方法最终生成的API地址为:/api/address/getall
- 接下来,使用_context对象来进行数据库操作,这个和EF是完全一样的~
至此,我的Demo代码就写完了,直接F5运行,浏览器手动敲个地址/api/address/getall就可以访问到数据库里面的前十条数据啦~
尝试.Net Core—使用.Net Core + Entity FrameWork Core构建WebAPI(一)的更多相关文章
- ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0
ASP.NET 5.0 将改名为 ASP.NET Core 1.0 ASP.NET MVC 6 将改名为 ASP.NET MVC Core 1.0 Entity Framework 7.0 将 ...
- [转帖]2016年时的新闻:ASP.NET Core 1.0、ASP.NET MVC Core 1.0和Entity Framework Core 1.0
ASP.NET Core 1.0.ASP.NET MVC Core 1.0和Entity Framework Core 1.0 http://www.cnblogs.com/webapi/p/5673 ...
- Professional C# 6 and .NET Core 1.0 - 38 Entity Framework Core
本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 38 Entity Framework ...
- ASP.NET Core 1.0: Using Entity Framework Core
伴随着ASP.NET Core 1.0发布的还有Entity Framework Core 1.0; 官方文档链接:https://docs.efproject.net/en/latest/platf ...
- [转]ASP.NET Core 1.0: Using Entity Framework Core 1.0 - Transaction
本文转自:http://blog.csdn.net/alvachien/article/details/51576961 跟Entity Framework之前的版本不同,Class DbContex ...
- ASP.NET Core 1.0: Using Entity Framework Core 1.0 - Transaction
跟Entity Framework之前的版本不同,Class DbContext不再有AcceptAllChanges()方法. 使用Transaction需要使用DbContext中的Databas ...
- 请问在 .NET Core 中如何让 Entity Framework Core 在日志中记录由 LINQ 生成的SQL语句?
using dotNET.Core; using Microsoft.Extensions.Logging; using System; using System.Collections.Generi ...
- 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)
在开发涉及到数据库的程序时,常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况,这时就需要进行数据库迁移. 实现数据库迁移有很多种办法,从手动管理各个版本的ddl脚本,到实现自己的mig ...
- Entity Framework Core 练习参考
项目地址:https://gitee.com/dhclly/IceDog.EFCore 项目介绍 对 Microsoft EntityFramework Core 框架的练习测试 参考文档教程 官方文 ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 读取关系数据
Reading related data¶ 9 of 9 people found this helpful The Contoso University sample web application ...
随机推荐
- php curl-class post
use \Curl\Curl; $curl = new Curl();$curl->setHeader('Content-Type', 'application/json');$curl-> ...
- java(1) 编程基础
1.classpath 环境变量 * 当java虚拟机需要运行一个类时,会在classpath 环境变量中所定义的路径下寻找所需的class文件 2.java 的基本语法 * java 语言是严格区分 ...
- NC 的简单使用
netcat被誉为网络安全界的’瑞士军刀’,相信没有什么人不认识它吧……一个简单而有用的工具,透过使用TCP或UDP协议的网络连接去读写数据.它被设计成一个稳定的后门工具,能够直接由其它程序和脚本轻松 ...
- vsCode_1.27.2
User Settings: 一,当前行高亮显示: "editor.renderLineHighlight": "line", 二,如何呈现空白字符(一般选no ...
- 题目1013:开门人和关门人(结构体自定义cmp排序)
题目链接:http://ac.jobdu.com/problem.php?pid=1013 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...
- openstack 中镜像状态详解 Image Statuses
Images in Glance can be in one the following statuses: queued The image identifier has been reserved ...
- 搭建IPv4专有网络
搭建IPv4专有网络 版权归属:阿里云网站 本教程将指引您搭建一个具有IPv4地址块的专有网络,并为专有网络中的ECS实例绑定一个弹性公网IP(EIP)进行公网访问. 步骤一:创建专有网络和交换机 ...
- iOS property中的strong 、weak、copy 、assign 、retain 、unsafe_unretained 与autoreleasing区别和作用详解
iOS5中加入了新知识,就是ARC,其实我并不是很喜欢它,因为习惯了自己管理内存.但是学习还是很有必要的. 在iOS开发过程中,属性的定义往往与retain, assign, copy有关,我想大家都 ...
- Jmeter TCP取样器配置及发送图解
最近在通过Jmeter测试TCP发送请求时,遇到相关问题,现记录 查看管方文档,TCP发送有三种启用方式: TCPClientImpl:文本数据,默认为这种 BinaryTCPClientImpl:传 ...
- jquery的$.each如何退出循环和退出本次循环
https://api.jquery.com/jQuery.each/ We can break the $.each() loop at a particular iteration by maki ...