.NET Core 入门






4.83/5 (39投票s)
在本文中,我们将了解 .NET Core 的特性以及 .NET Framework(现有)的简要概述。我们将讨论在新环境 .NET Core 中进行了哪些更改/添加。
将要讨论的主题
- .NET Framework 简要概述
- .NET Core 是什么?
- ASP.NET Core 是什么?
- 如何开始?
- 初始示例应用程序的详细概述
- Global.json
- 属性
- wwwroot
- 控制器 (Controller)
- 视图
- appsettings.json
- bower.json
- bundleconfig.json
- program.cs
- project.json
- startup.cs
- web.config
- 使用以下工具处理数据
- ASP.NET Core &
- Entity Framework-7 (Core)
- MVC-6 (Core)
好的,让我们一个接一个地开始,以理清我们在 .NET 这个神奇世界中的想法。
.NET Framework
.NET Framework(发音为 dot net)是由 Microsoft 开发的软件开发平台。它提供了允许开发人员开发应用程序的工具和库。Microsoft 于 1990 年代末开始开发 .NET Framework,最初名为 Next Generation Windows Services (NGWS)。到 2001 年底,.NET 1.0 的第一个测试版发布了。
.NET Framework 版本
在这里,我提供了对 .NET Framework 版本评估的简要概述,这是我们都知道的,但只是为了更好地理解 .NET 的思想和路线图。我们都了解这些版本,但新公告呢?.NET Core 是另一个框架吗?好的,让我们慢慢来,一步一步,我们将揭开所有这些问题。
到目前为止,我们知道所有这些版本,但新公告呢?.NET Core 是另一个框架吗?好的,让我们慢慢来,一步一步,我们将揭开所有这些问题。
.NET 今日
Microsoft 今年宣布了许多令人兴奋的新 .NET 创新。其中,最强大的是开源的跨平台开发(任何开发人员,任何应用程序,任何平台)。了解更多……
.NET Core
简单来说,.NET Core 是一个现代、轻量级、高性能的模块化平台,用于创建运行在跨平台(Windows、Linux 和 Mac)上的 Web 应用程序和 RESTful API。它是 .NET Framework(完整版)的一个较小的集合/子集,由 Microsoft 和 .NET 社区在GitHub 上维护。
.NET Core 功能
- 跨平台,可在 Windows、macOS 和 Linux 上运行
- 开源
- 命令行工具,可在命令行中使用
- 通过.NET Standard 库与 .NET Framework、Xamarin 和 Mono兼容
- 灵活部署
.NET Core 平台:.NET Core 平台由多个组件组成
- CoreFX - .NET Core 基础库
- CoreCLR - .NET Core 运行时
- CLI - .NET Core 命令行工具
- Roslyn - .NET 编译器平台
.NET Core vs .NET Framework 图
.NET Core 版本
- .NET Core 1.1 于 2016 年 11 月 16 日发布
- .NET Core 1.0 预览版 1 于 2016 年 10 月 24 日发布
- .NET Core 0.1 于 2016 年 9 月 13 日发布
- .NET Core 0.0 于 2016 年 6 月 27 日发布
- .NET Core RC2 (Release Candidate) 于 2016 年 5 月 16 日发布
- .NET Core RC1 (Release Candidate) 于 2015 年 11 月 18 日发布
下载最新的 .NET Core SDK(运行时 + 命令行工具)或仅运行时。
.NET Core 支持
最初,.NET Core 支持四种类型的应用程序开发,其中我们将重点关注 ASP.NET Core 应用程序开发。
- .NET Core Web 应用
- 命令行应用
- 库,以及
- 通用 Windows 平台 (UWP) 应用
ASP.NET Core
ASP.NET Core 是一个重写的、全新的开源 ASP.NET Web 框架,用于构建可在完整 .NET Framework 和 .NET Core 上运行的基于 Web 的应用程序(Web 应用、IoT 应用和移动后端)。
ASP.NET Core 功能
- 跨平台(Windows、Mac 和 Linux)开发和运行
- 开源
- 基于 .NET Core 运行时以及 .NET Framework 构建
- 动态编译功能
- 内置依赖注入 (DI)
- MVC & Web API Controller 已统一,继承自同一个基类
- 新的轻量级、模块化 HTTP 请求管道
- 可在 IIS 上托管或在自己的进程中自托管
- 完全作为 NuGet 包分发
- 智能工具(如 Bower、Grunt & Gulp)
如何开始?
这是Windows 的快速安装指南。
步骤
- 安装 Visual Studio 2015(提供功能齐全的开发环境)
- 确保您已安装 Visual Studio 2015 更新 3
- 安装适用于 Visual Studio 的 .NET Core 工具预览版
- 创建新的 .NET Core 项目
- 运行应用程序
了解更多关于如何开始的信息……
ASP.NET Core 初始应用程序的结构
Global.json
这是一个用于 ASP.NET 全局配置文件(包含解决方案信息/元数据)的 JSON 架构。在此文件中,我们可以配置 SDK 的版本、体系结构或指定目标处理器体系结构、目标运行时的运行时。让我们详细了解这些属性。
- Projects:指定要搜索包含项目的文件夹
- Packages:指定包位置
- Sdk:指定有关 SDK 的信息
这是我们默认的 global.json 属性。
{
"projects": [ "src", "test" ],
"sdk": {
"version": "1.0.0-preview2-003131"
}
}
要获取其他属性信息详情,请访问 > http://json.schemastore.org/global
"properties": {
"projects": {
"type": "array",
"description":
"A list of project folders relative to this file.",
"items": {
"type": "string"
}
},
"packages": {
"type": "string",
"description": "The location to store packages"
},
"sdk": {
"type": "object",
"description": "Specify information about the SDK.",
"properties": {
"version": {
"type": "string",
"description": "The version of the SDK to use."
},
"architecture": {
"enum": [ "x64", "x86" ],
"description":
"Specify which processor architecture to target."
},
"runtime": {
"enum": [ "clr", "coreclr" ],
"description": "Chose which runtime to target."
}
}
}
}
属性 > launchSettings.json
这是 ASP.NET DebugSettings.json 文件的 JSON 架构。我们可以在此使用 IDE 界面配置调试配置文件,另一种设置属性的方法是 launchSetting.json 文件。右键单击“项目属性”>“调试”。
这是 launchSetting.json 中默认的配置属性。
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "https://:17023/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"CoreMVC": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "https://:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
我们可以使用与 IISExpress
相同的命令将生产配置文件添加到 json 文件中。基于此环境配置文件,我们可以显示/隐藏不同环境下的 HTML 标签,这被称为处理多环境。稍后我们将讨论它。
"IIS Production": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
新的调试配置文件将如下所示:
让我们详细了解这些属性
commandLineArgs
:传递给命令的参数workingDirectory
:设置命令的工作目录launchBrowser
:如果应启动浏览器,则设置为true
launchUrl
:在浏览器中启动的相对 URLenvironmentVariables
:将环境变量设置为键/值对sdkVersion
:设置 SDK 的版本
要获取其他属性信息详情,请访问 > http://json.schemastore.org/launchsettings。
"properties": {
"commandLineArgs": {
"type": "string",
"description": "The arguments to pass to the command.",
"default": ""
},
"workingDirectory": {
"type": "string",
"description": "Sets the working directory of the command."
},
"launchBrowser": {
"type": "boolean",
"description": "Set to true if the browser should be launched.",
"default": false
},
"launchUrl": {
"type": "string",
"description": "The relative URL to launch in the browser.",
"format": "uri"
},
"environmentVariables": {
"type": "object",
"description": "Set the environment variables as key/value pairs.",
"additionalProperties": {
"type": "string"
}
},
"sdkVersion": {
"type": "string",
"description": "Sets the version of the SDK."
}
}
wwwroot:这是关于直接向客户端提供静态文件的一切。我们需要提供静态文件。我们需要做的就是在 startup 类 Configure
方法中添加扩展方法 UseStaticFiles()
。
然后,在 project.json 中解析静态文件的依赖包“Microsoft.AspNetCore.StaticFiles
”:“1.0.0
”。
控制器 (Controller)
ASP.NET Core Controller 已统一,MVC Controller(Controller 基类)和 WebAPI Controller(ApiController 基类)之间没有区别。正如您所见,我将它们并排放置以显示 MVC 和 WebAPI Controller 之间的区别,这两个 Controller 都继承自同一个 Controller。
视图
ASP.NET Core MVC 视图是 .cshtml 文件,正如我们之前从 ASP.NET MVC 视图中知道的那样,它们使用 Razor 视图引擎来渲染视图。在这里,我展示了 MVC 文件夹结构以及我们 ASP.NET Core 应用程序中相关的 .cshtml 文件。
appsettings.json
这是应用程序配置文件,其中包含键/值对的配置值。以前,此配置存储在 web.config 文件中。
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
我们可以将连接字符串添加到 appsetting 文件中,然后在 startup 中访问连接。
"ConnectionStrings": {
"dbConn": "Server=DESKTOP-5B67SHH;
Database=TicketBooking;Trusted_Connection=True;
MultipleActiveResultSets=true"
}
在 startup 文件中,我们在 ConfigureService
方法中添加了我们的服务,以通过连接字符串启用数据库连接。
public void ConfigureServices(IServiceCollection services)
{
//Add database services.
var connectionString = this.Configuration.GetConnectionString("dbConn");
services.AddDbContext<TicketBookingContext>
(options => options.UseSqlServer(connectionString));
// Add framework services.
services.AddMvc();
}
var connectionString = this.Configuration.GetConnectionString("dbConn");
在这里,GetConnectionString
是一个扩展方法,它传递连接名称“dbConn
”。
bower.json
Bower 是一个包管理器,当我们在 json 文件中添加/删除列出的包时,它会自动添加/更新客户端包(如 bootstrap、jquery 等)。
{
"name": "asp.net",
"private": true,
"dependencies": {
"bootstrap": "3.3.6",
"jquery": "2.2.0",
"jquery-validation": "1.14.0",
"jquery-validation-unobtrusive": "3.2.6"
}
}
这是列出的客户端依赖项,还有另一种依赖项称为服务器端依赖项。这里的 private: true
表示它将拒绝发布,防止意外发布私有存储库。
要更改 bower 安装位置,请打开 .bowerrc 并更改目录值。
{
"directory": "wwwroot/lib"
}
在这里,您可以看到依赖项已安装在 wwwroot/lib 文件夹中,这是初始值。
bundleconfig.json
将任何项目中的 JavaScript、CSS 和 HTML 文件打包和最小化。下载 BundlerMinifierVsix 并安装在 Visual Studio 2015 中。重启 IDE。
任务运行程序浏览器将会出现,要全部更新,请右键单击 > 更新所有文件 > 运行。
最后,将生成输出文件。
这是 bundleconfig.json 的样子
// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
{
"outputFileName": "wwwroot/css/site.min.css",
// An array of relative input file paths. Globbing patterns supported
"inputFiles": [
"wwwroot/css/site.css"
]
},
{
"outputFileName": "wwwroot/js/site.min.js",
"inputFiles": [
"wwwroot/js/site.js"
],
// Optionally specify minification options
"minify": {
"enabled": true,
"renameLocals": true
},
// Optionally generate .map file
"sourceMap": false
}
]
program.cs
这是任何 ASP.NET Core 应用程序的关键部分,它准备主机来运行所有配置的服务。这是 program.cs 代码片段。
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
在 program.cs 类中,只需使用 WebHostBuilder
配置和启动主机。如我们所知,.NET Core 应用程序是一个控制台应用程序,需要由主机执行。WebHostBuilder
通过 UseKestrel()
扩展方法创建主机来引导服务器,这意味着 Kestrel 服务器将托管应用程序。还有一个用于 IIS 服务器的 UseIISIntegration()
扩展方法。下面是一个图表,说明了 IIS 和 ASP.NET Core 应用程序之间的流程。
来源:ASP.NET Core 模块概述 作者:Tom Dykstra, Rick Strahl, and Chris Ross
WebHostBuilder
负责创建引导应用程序服务器的主机。了解有关托管的更多信息……我们可以说 .NET Core 应用程序需要一个主机来启动,该主机定义了将使用哪个服务器,从哪里获取内容文件,并指定启动(中间件)服务。
project.json
project.json 文件存储应用程序信息、依赖项和编译器设置。它有几个部分,如 Dependencies、Tools、Frameworks、Build Options 等等。在这里,我展示了默认 project.json 的内容。
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
"Microsoft.AspNetCore.Routing": "1.0.1",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
},
"tools": {
"BundlerMinifier.Core": "2.0.238",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"prepublish": [ "bower install", "dotnet bundle" ],
"postpublish": [ "dotnet publish-iis
--publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
}
}
让我们一步一步地探索其中的不同部分
project.json > Dependencies
此部分使用键/值对管理项目依赖项,如果需要,我们可以添加新的依赖项,智能感知将帮助我们包含名称和版本。
正如您从上面的图片中看到的,我添加了三个用于数据库服务的新包,智能感知通过显示该包的版本来帮助我。当我保存更改时,它会自动从 NuGet 恢复所需的依赖项。
project.json > Tools:此部分管理和列出命令行工具,我们可以看到 IISIntegration
。默认情况下会添加 Tools,这是一个包含 dotnet publish IIS 命令的工具,用于在 IIS 上发布应用程序。
"tools": {
"BundlerMinifier.Core": "2.0.238",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
}
EntityFrameworkCore Tools(EF Core 的命令行工具)包含命令
对于包管理器控制台
- Scaffold-DbContext
- Add-Migration
- Update-Database
对于命令窗口
- dotnet ef dbcontext scaffold
这里显示了 EF 命令,请仔细查看。如果我们禁用 EntityFrameworkCore
Tools 并运行命令,它将在程序包管理器控制台中显示以下错误:
project.json > Frameworks
定义应用程序支持的框架,我们可以在此部分配置使用多个框架。
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
},
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
}
让我们再澄清一下,在 framework 部分,我们正在针对 netcoreapp1.0 框架。通过配置 import 部分,我们可以使用与应用程序目标版本不同的几个目标包/类库。这里,“dotnet5.6”用于较旧的 .NET Core 预览版本,而“portable-net45+win8”用于可移植类库 (PCL) profile,这被称为目标框架 Monikers(TFM)。我们可以通过在 framework 部分添加“net461”:{} 来使用多个框架。
"frameworks": {
"net461": {
"dependencies": {
}
},
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
}
},
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
}
您可能会注意到,我们必须将 Microsoft.NETCore.App
依赖项从全局依赖项移动到特定的框架依赖项部分。
这就是我们使用多个框架/运行时支持。
project.json > Build Options
在构建应用程序时传递给编译器的选项。
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
}
project.json > RuntimeOptions
管理应用程序运行时服务器垃圾收集。
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
}
project.json > PublishOptions
这定义了在发布应用程序时包含/排除到输出文件夹的文件/文件夹。
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config"
]
}
project.json > Scripts
Scripts
是一个对象类型,指定在构建或发布应用程序时运行哪些脚本。
"scripts": {
"prepublish": [ "bower install", "dotnet bundle" ],
"postpublish": [ "dotnet publish-iis
--publish-folder %publish:OutputPath%
--framework %publish:FullTargetFramework%" ]
}
了解有关 project.json 文件的更多信息……
startup.cs
这是每个 ASP.NET Core 应用程序的入口点,它提供了应用程序所需的各种服务。这里有一个图表,显示了应用程序首次运行时在运行时会发生什么。
在 Startup
类中,有几个方法承担着不同的职责。在这里,我将它们分开,第一个是 Startup
类的构造函数。在构造函数中,将 IHostingEnvironment
实例作为参数传递,以获取 Web 主机环境的详细信息。
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json",
optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
ConfigurationBuilder
实例调用多个配置源的扩展方法,然后像链式调用一样按顺序链接在一起,形成一个流畅的 API。
public IConfigurationRoot Configuration { get; }
IConfigurationRoot
强制在应用程序运行时重新加载配置值,并且配置数据发生更改。下一个方法是 ConfigureServices,它在 Configure
方法之前被调用。在此部分,我们可以配置我们在应用程序运行时所需的各种服务。将 IServiceCollection
实例作为参数传递。IServiceCollection
指定了不同服务的集合。
public void ConfigureServices(IServiceCollection services)
{
//Add framework services.
services.AddMvc();
//Add database services.
var connectionString =
this.Configuration.GetConnectionString("dbConn");
services.AddDbContext<TicketBookingContext>
(options => options.UseSqlServer(connectionString));
}
在 Startup
类中,Configure()
方法处理 HTTP 请求。
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
}
完整的 startup 如下所示:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json",
optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
web.config
在 ASP.NET Core 中,应用程序配置现在存储在 appsettings.json 文件中。以前,它存储在 web.config 文件中。这是默认的 web.config 文件外观:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json.
Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*"
verb="*" modules="AspNetCoreModule"
resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%"
arguments="%LAUNCHER_ARGS%"
stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout"
forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
Web.config 仅用于配置,而托管在 IIS 中。在 handler 部分,IIS 通过将请求传递给 ASP.NET Core Module 来处理请求。
<handlers>
<add name="aspNetCore" path="*"
verb="*" modules="AspNetCoreModule"
resourceType="Unspecified" />
</handlers>
我们可以在 IIS 中通过 web.config 指定环境。
<aspNetCore processPath="dotnet"
arguments=".\CoreMVC.dll" stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout"
forwardWindowsAuthToken="false">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT"
value="Development" />
</environmentVariables>
</aspNetCore>
使用 ASP.Net Core MVC 处理数据(CRUD)
数据库创建
使用 SSMS 创建一个新数据库,命名为“TicketBooking
”。复制下面的查询并在 SSMS 的查询编辑器中运行它。
USE [TicketBooking]
GO
/****** Object: Table [dbo].[Ticket] Script Date: 11/22/2016 1:25:55 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ticket](
[TicketID] [int] NOT NULL,
[DestinationFrom] [nvarchar](50) NULL,
[DestinationTo] [nvarchar](50) NULL,
[TicketDate] [datetime] NULL,
[TicketFee] [numeric](18, 2) NULL,
CONSTRAINT [PK_Ticket] PRIMARY KEY CLUSTERED
(
[TicketID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
反向工程
添加依赖包
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools":"1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1"
添加工具
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
IDE 将自动恢复包。
从现有数据库创建 EF 模型。
- 工具 –> NuGet 程序包管理器 –> 程序包管理器控制台
- 运行以下命令
Scaffold-DbContext "Server=DESKTOP-5B67SHH;
Database=TicketBooking;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
正如您所见,模型已在 Models 文件夹中创建。如果数据库有任何更改,请使用以下命令重写来自数据库的实体。
Scaffold-DbContext "Server=DESKTOP-5B67SHH;
Database=TicketBooking;Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force
背景
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace CoreMVC.Models
{
public partial class TicketBookingContext : DbContext
{
public TicketBookingContext
(DbContextOptions<TicketBookingContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Ticket>(entity =>
{
entity.Property(e => e.TicketId).HasColumnName("TicketID");
entity.Property(e => e.DestinationFrom).HasMaxLength(50);
entity.Property(e => e.DestinationTo).HasMaxLength(50);
entity.Property(e => e.TicketDate).HasColumnType("datetime");
entity.Property(e => e.TicketFee).HasColumnType("numeric");
entity.Property(e => e.Vat)
.HasColumnName("VAT")
.HasColumnType("numeric");
});
}
public virtual DbSet<Ticket> Ticket { get; set; }
}
}
MVC Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreMVC.Models;
using Microsoft.EntityFrameworkCore;
// For more information on enabling MVC for empty projects,
// visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace CoreMVC.Controllers
{
public class TicketsController : Controller
{
private TicketBookingContext _ctx = null;
public TicketsController(TicketBookingContext context)
{
_ctx = context;
}
// GET: Tickets/Index/
public async Task<IActionResult> Index()
{
List<Ticket> tickets = null;
try
{
tickets = await _ctx.Ticket.ToListAsync();
}
catch (Exception ex)
{
ex.ToString();
}
return View(tickets);
}
// GET: Tickets/Create
public IActionResult Create()
{
return View();
}
[ValidateAntiForgeryToken, HttpPost]
public async Task<IActionResult> Create(Ticket ticket)
{
if (ModelState.IsValid)
{
try
{
_ctx.Add(ticket);
await _ctx.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ex.ToString();
}
}
return View(ticket);
}
// GET: Tickets/Details/5
public async Task<IActionResult> Details(int? id)
{
object ticket = null;
try
{
if ((id != null) && (id > 0))
{
ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
}
}
catch (Exception ex)
{
ex.ToString();
}
return View(ticket);
}
// GET: Tickets/Edit/5
public async Task<IActionResult> Edit(int? id)
{
object ticket = null;
try
{
if ((id != null) && (id > 0))
{
ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
}
}
catch (Exception ex)
{
ex.ToString();
}
return View(ticket);
}
[ValidateAntiForgeryToken, HttpPost]
public async Task<IActionResult> Edit(int id, Ticket ticket)
{
if (id == ticket.TicketId)
{
if (ModelState.IsValid)
{
try
{
_ctx.Update(ticket);
await _ctx.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException dce)
{
if (!TicketExists(ticket.TicketId))
{
return NotFound();
}
else
{
dce.ToString();
}
}
return RedirectToAction("Index");
}
}
return View(ticket);
}
// GET: Tickets/Delete/5
public async Task<IActionResult> Delete(int? id)
{
object ticket = null;
try
{
if ((id != null) && (id > 0))
{
ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
if (ticket == null)
{
return NotFound();
}
}
}
catch (Exception ex)
{
ex.ToString();
}
return View(ticket);
}
// POST: Tickets/Delete/5
[ValidateAntiForgeryToken, HttpPost, ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
try
{
var ticket = await _ctx.Ticket.SingleOrDefaultAsync(m => m.TicketId == id);
_ctx.Ticket.Remove(ticket);
await _ctx.SaveChangesAsync();
}
catch (Exception ex)
{
ex.ToString();
}
return RedirectToAction("Index");
}
private bool TicketExists(int id)
{
return _ctx.Ticket.Any(e => e.TicketId == id);
}
}
}
WebAPI Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CoreMVC.Models;
using Microsoft.EntityFrameworkCore;
// For more information on enabling Web API for empty projects,
// visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace CoreMVC.Controllers
{
[Route("api/[controller]")]
public class TicketController : Controller
{
private TicketBookingContext _ctx = null;
public TicketController(TicketBookingContext context)
{
_ctx = context;
}
// GET: api/Ticket/GetTicket
[HttpGet("GetTicket"), Produces("application/json")]
public async Task<object> GetTicket()
{
List<Ticket> Tickets = null;
object result = null;
try
{
using (_ctx)
{
Tickets = await _ctx.Ticket.ToListAsync();
result = new
{
Tickets
};
}
}
catch (Exception ex)
{
ex.ToString();
}
return Tickets;
}
// GET api/Ticket/GetTicketByID/5
[HttpGet("GetTicketByID/{id}"),
Produces("application/json")]
public async Task<Ticket> GetTicketByID(int id)
{
Ticket contact = null;
try
{
using (_ctx)
{
contact = await _ctx.Ticket.FirstOrDefaultAsync
(x => x.TicketId == id);
}
}
catch (Exception ex)
{
ex.ToString();
}
return contact;
}
// POST api/Ticket/PostTicket
[HttpPost, Route("PostTicket"),
Produces("application/json")]
public async Task<object> PostTicket([FromBody]Ticket model)
{
object result = null; string message = "";
if (model == null)
{
return BadRequest();
}
using (_ctx)
{
using (var _ctxTransaction = _ctx.Database.BeginTransaction())
{
try
{
_ctx.Ticket.Add(model);
await _ctx.SaveChangesAsync();
_ctxTransaction.Commit();
message = "Saved Successfully";
}
catch (Exception e)
{
_ctxTransaction.Rollback();
e.ToString();
message = "Saved Error";
}
result = new
{
message
};
}
}
return result;
}
// PUT api/Ticket/PutTicket/5
[HttpPut, Route("PutTicket/{id}")]
public async Task<object>
PutContact(int id, [FromBody]Ticket model)
{
object result = null; string message = "";
if (model == null)
{
return BadRequest();
}
using (_ctx)
{
using (var _ctxTransaction = _ctx.Database.BeginTransaction())
{
try
{
var entityUpdate = _ctx.Ticket.FirstOrDefault
(x => x.TicketId == id);
if (entityUpdate != null)
{
entityUpdate.DestinationFrom = model.DestinationFrom;
entityUpdate.DestinationTo = model.DestinationTo;
entityUpdate.TicketFee = model.TicketFee;
await _ctx.SaveChangesAsync();
}
_ctxTransaction.Commit();
message = "Entry Updated";
}
catch (Exception e)
{
_ctxTransaction.Rollback(); e.ToString();
message = "Entry Update Failed!!";
}
result = new
{
message
};
}
}
return result;
}
// DELETE api/Ticket/DeleteTicketByID/5
[HttpDelete, Route("DeleteTicketByID/{id}")]
public async Task<object> DeleteContactByID(int id)
{
object result = null; string message = "";
using (_ctx)
{
using (var _ctxTransaction = _ctx.Database.BeginTransaction())
{
try
{
var idToRemove = _ctx.Ticket.SingleOrDefault(x => x.TicketId == id);
if (idToRemove != null)
{
_ctx.Ticket.Remove(idToRemove);
await _ctx.SaveChangesAsync();
}
_ctxTransaction.Commit();
message = "Deleted Successfully";
}
catch (Exception e)
{
_ctxTransaction.Rollback(); e.ToString();
message = "Error on Deleting!!";
}
result = new
{
message
};
}
}
return result;
}
}
}
输出
希望这会有所帮助!
参考文献
- https://en.wikipedia.org/wiki/.NET_Framework
- https://en.wikipedia.org/wiki/.NET_Framework_version_history
- https://dotnet.github.io
- https://docs.microsoft.com/en-us/aspnet/core
- https://github.com/aspnet
- https://www.microsoft.com/net/core/platform
- https://github.com/dotnet/core
- https://docs.microsoft.com/en-us/dotnet/articles/core/index
- https://codeproject.org.cn/Articles/1115771/NET-CORE-MVC-ANGULARJS-STARTUP
- https://codeproject.org.cn/Articles/1118189/CRUD-USING-NET-CORE-ANGULARJS-WEBAPI
- https://docs.microsoft.com/en-us/aspnet/core