前言 Asp.Net Core是基於Framwork4.X,與早期 MVC相比,Core 雲服務支持更好,一個Core工程項目既包含WebAPI,同時也可以包含MVC的Webs發布。
第一篇 通過Microsoft Visual Studio(本案例版本:2019)快速創建Core MVC連接Sqlserver數據庫
說明:本篇blog簡單介紹Asp.Net Core快速創建Sqlserver數據庫的CRUD(添加、刪除、查找、修改)的基本案例,重點介紹Core MVC入門實操,僅做參考!大俠繞步☺
學習目標:
1、初步了解Core平台MVC(模型-控制器-視圖)框架結構;
2、掌握使用Vs2019 IDE工具快速搭建Core項目;
3、學習Core MVC配置、Sql配置以及注冊服務等方法;
前期准備:安裝Vs2017以上版本(集成Core SDK環境),安裝Sqlserver2008(含)以上版本的數據庫。
一、創建項目
為了快速搭建MVC項目我們默認選擇帶有(模型-視圖-控制器)的.Net Core Webs項目。。

繼續下一步,項目名稱輸入MVC_SQL_Test

繼續下一步,Core默認版本選擇3.1

說明:Core 標准的MVC目錄結構與之早期MVC類似,主要由Models(模型)、Controllers(控制器)、VIews(視圖)三層架構組成,Startup.cs主要用來注冊服務。
另外,Core MVC與以往的最大的區別是支持跨平台,及以包(Docker)的方式發布Linux平台。

二、導入Sqlserver中間件程序包
右鍵選擇項目資源,點擊NuGet程序包,選擇“Microsoft.EntityFrameworkCore.SqlServer”(V3.0)和“Microsoft.EntityFrameworkCore.Tool”(V3.0)以及:"EntityFramework.SqlServerCompact" (V4.1)

三、創建Sqlserver連接
點擊菜單欄【視圖】->【其它窗口】->【程序包管理台控制器】,輸入以下命令由Vs自動創建。
Scaffold-DbContext “Data Source=127.0.0.1;Initial Catalog=InfoUser;User ID=sa;Password=sa;MultipleActiveResultSets=true;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

四、創建Sqlserver數據庫
在Sqlserver中創建數據庫名稱為InfoData,數據表為UserData,三個字段分別為:UserId,UserName和Password。

五、創建控制器視圖
右鍵選擇資源管理器【Controllers】->添加【控制器】->選擇【視圖使用Entity Framework的MVC控制器】
此處注意:很多朋友創建Controllers時會報錯提示model缺少“primary key”,即自動關聯的數據庫缺少主鍵;

這時需要在Models中的UserData.cs類中添加主鍵[key],如下圖所示:

通過Vs2019工具手動創建控制器:右鍵點擊"Controllers",添加“控制器”,在打開的窗口中選擇“Entity Framework的MVC控制器”,


六、注冊服務和路由
1、在appsettings.json文件中配置Sqlserver連接信息。
"Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "MVCSqlContext": "Server=localhost;Database=InfoUser;User ID=sa;Password=sa;" } }
2、在InfoUserContenxt.cs中注釋掉以下代碼

3、在Startups文件中加入下面的代碼
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MVC_SQL_Test.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace MVC_SQL_Test { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); //下面為加入的數據庫服務,注意MVCSqlContext修改為自己的文件名 services.AddDbContext<InfoUserContext>(options => //services.AddDbContext<InfoUserContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MVCSqlContext"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=UserDatas}/{action=Index}/{id?}"); }); } } }
接着將Startup.cs文件中 pattern: "{controller=Home}/{action=Index}/{id?}");語句中Home改為用戶頁,即pattern: "{controller=UserDatas}/{action=Index}/{id?}");項目重新生成后運
