CodeFirst從零開(kāi)始搭建Asp.Net Core2.0網(wǎng)站
一步步教大家如何搭建Asp.Net Core2.0網(wǎng)站,以下所有都是建立在.NETCore2.0環(huán)境已經(jīng)搭建好
右鍵解決方案>新建項(xiàng)目>
選擇Web>ASP.NETCoreWeb應(yīng)用程序(.NET Core)

選擇Web應(yīng)用程序,暫時(shí)不選擇啟用Docker,身份驗(yàn)證選擇個(gè)人用戶賬戶(會(huì)自動(dòng)生成一系列和用戶認(rèn)證的代碼)


隨后生代碼層次目錄如下:

其中會(huì)包含身份信息的相關(guān)實(shí)現(xiàn),比如相關(guān)實(shí)體信息(user)之類的,如果想對(duì)擴(kuò)展微軟自動(dòng)的生成的用戶實(shí)體類,可在Models中的ApplicationUser下擴(kuò)展,在此ApplicationUser中添加屬性即可:比如添加叫WeChatId屬性,添加后如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace DotNetCore20.Web.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
/// <summary>
/// 微信Id
/// </summary>
public string WeChatId { get; set; }
}
}
在之后生成運(yùn)行并遷移,數(shù)據(jù)庫(kù)的AspNetUsers中就會(huì)多出WeChatId 屬性.
一:安裝引用
nugnet恢復(fù)引用失效時(shí),可在程序包管理控制臺(tái)輸入:
dotnet restore 即可

會(huì)發(fā)現(xiàn)在恢復(fù)指令后在NuGet中會(huì)有一個(gè)Microsoft.VisualStudio.Web.CodeGeneration.Design的報(bào)錯(cuò),信息如下:
已使用“.NETPortable,Version=v0.0,Profile=Profile259, .NETFramework,Version=v4.6.1”而不是項(xiàng)目目標(biāo)框架“.NETCoreApp,Version=v2.0”還原了包“Microsoft.Composition 1.0.27”。這可能會(huì)導(dǎo)致兼容性問(wèn)題
這個(gè)庫(kù)是ASP.NET Core的代碼生成工具。包含用于生成控制器和視圖的dotnet-aspnet-codegenerator命令,暫時(shí)可先卸載,不影響項(xiàng)目運(yùn)行.
對(duì)項(xiàng)目類庫(kù)的引用有以下幾種方式
1.Nuget去安裝(官網(wǎng)https://www.nuget.org/packages/)
2.右鍵依賴項(xiàng)點(diǎn)擊菜單中的添加引用
3.可在程序包管理控制臺(tái)輸入:Install-Package引用類庫(kù)名稱
4.可右鍵編輯csproj工程文件進(jìn)行添加,然后執(zhí)行dotnet restore

二.創(chuàng)建實(shí)體程序集
右鍵解決方案>添加項(xiàng)目>

首先創(chuàng)建抽象類,供Entity實(shí)體繼承,主要為每個(gè)實(shí)體提供公用屬性
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text;
namespace DotNetCore20.Entity.Core
{
/// <summary>
/// DB表基底
/// </summary>
[Serializable]
public abstract partial class BaseEntity
{
/// <summary>
/// Id
/// </summary>
[DataMember]
public long Id { get; set; }
/// <summary>
/// DB 資料版號(hào)
/// </summary>
[Timestamp]
public byte[] RowVersion { get; set; }
/// <summary>
/// 創(chuàng)建時(shí)間
/// </summary>
[DataMember]
public DateTime CreateTime { get; set; }
/// <summary>
/// 更新時(shí)間
/// </summary>
[DataMember]
public DateTime UpdateTime { get; set; }
/// <summary>
/// 狀態(tài)
/// </summary>
[DataMember]
public EnumState State { get; set; }
}
/// <summary>
/// 狀態(tài)
/// </summary>
public enum EnumState
{
/// <summary>
/// 刪除
/// </summary>
Delete = 1,
/// <summary>
/// 正常
/// </summary>
Normal = 0,
}
}
添加一個(gè)UserExtend用戶擴(kuò)展類(Entity):
using DotNetCore20.Entity.Core;
using System;
using System.Runtime.Serialization;
namespace DotNetCore20.Entity
{
[DataContract]
public class UserExtend : BaseEntity
{
/// <summary>
/// 用戶Id
/// </summary>
[DataMember]
public long UserId { get; set; }
/// <summary>
/// 昵稱
/// </summary>
[DataMember]
public long NickName { get; set; }
}
}
三.創(chuàng)建數(shù)據(jù)層

添加引用
DAL層需要用到EF實(shí)體映射相關(guān)和我們自己前面定義的Entity中的UserExtend實(shí)體表,所以要添加相關(guān)引用,DotNetCore20.Entity和 Microsoft.EntityFrameworkCore.Tools
快捷鍵:Ctrl+Alt+o 打開(kāi)程序包管理器輸入以下:
install-package Microsoft.EntityFrameworkCore.Tools

如果是網(wǎng)絡(luò)限制下載失敗,推薦把nuget鏡像改為博客園資源,方法如下:
右鍵解決方案>管理解決方案的nuget程序包.顯示如下:


新建一個(gè)數(shù)據(jù)上下文類,目錄結(jié)構(gòu)如下:

DotNetCoreDbContext內(nèi)部代碼改為以下:
using DotNetCore20.Entity;
using Microsoft.EntityFrameworkCore;
namespace DotNetCore20.DAL.DbContext
{
public class DotNetCoreDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public DotNetCoreDbContext(DbContextOptions<DotNetCoreDbContext> options) : base(options)
{
}
public DbSet<UserExtend> UserExtend { get; set; }
}
}
在此基本的實(shí)體映射相關(guān)的代碼都完畢,現(xiàn)在還有一步,就是數(shù)據(jù)庫(kù)連接字符串的配置
首先打開(kāi)appsettings.json文件,在ConnectionStrings節(jié)點(diǎn)下增加以下
增加后如下:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDefaultDb;Trusted_Connection=True;MultipleActiveResultSets=true",
"DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}
再打開(kāi)web網(wǎng)站下的Startup文件,在ConfigureServices方法中添加一下行:
//自定義數(shù)據(jù)庫(kù)連接字符串
services.AddDbContext<DotNetCoreDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));
增加后如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using DotNetCore20.Web.Data;
using DotNetCore20.Web.Models;
using DotNetCore20.Web.Services;
using DotNetCore20.DAL.DbContext;
namespace DotNetCore20.Web
{
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.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//自定義數(shù)據(jù)庫(kù)連接字符串
services.AddDbContext<DotNetCoreDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
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)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
運(yùn)行程序,點(diǎn)擊登陸(只要訪問(wèn)數(shù)據(jù)庫(kù)的操作都可),出現(xiàn)錯(cuò)誤頁(yè)面:

點(diǎn)擊應(yīng)用遷移
,即自動(dòng)遷移數(shù)據(jù)庫(kù).
由于兩個(gè)數(shù)據(jù)庫(kù),只會(huì)自動(dòng)遷移關(guān)于用戶的表AspNetUsers,
所以還得VS中程序包管理器中下命令遷移.
Add-Migration firstMigration -Context DotNetCoreDbContext
以上命令執(zhí)行后再執(zhí)行以下命令:
Update-Database -ContextDotNetCoreDbContext;
然后查看數(shù)據(jù)庫(kù)會(huì)發(fā)現(xiàn)多出兩個(gè)數(shù)據(jù)庫(kù),
以DotNetCoreDefaultDb生成的為例,會(huì)生成如下表:

其中AspNetUsers就中會(huì)有之前添加的WeChatId字段

然后再次運(yùn)行程序:

這樣一個(gè)完整的Asp.NetCore2.0網(wǎng)站就初步運(yùn)行起來(lái)了
下一篇將在DAL層增加Repository和UnitWorks,完成簡(jiǎn)單crud的統(tǒng)一管理
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
win10下ASP.NET Core部署環(huán)境搭建步驟
這篇文章主要以圖文結(jié)合的方式介紹了win10下ASP.NET Core部署環(huán)境搭建步驟,感興趣的小伙伴們可以參考一下2016-07-07
asp.net MVC利用自定義ModelBinder過(guò)濾關(guān)鍵字的方法(附demo源碼下載)
這篇文章主要介紹了MVC利用自定義ModelBinder過(guò)濾關(guān)鍵字的方法,結(jié)合實(shí)例形式詳細(xì)分析了自定義ModelBinder過(guò)濾關(guān)鍵字的原理與具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-03-03
.NET Core 2.0遷移小技巧之MemoryCache問(wèn)題修復(fù)解決的方法
這篇文章主要給大家介紹了關(guān)于.NET Core 2.0遷移小技巧之MemoryCache問(wèn)題修復(fù)解決的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08
.Net項(xiàng)目中NLog的配置和使用實(shí)例詳解
這篇文章主要給大家介紹了關(guān)于.Net項(xiàng)目中NLog的配置和使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用.Net具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
.Net Core+Angular Cli/Angular4開(kāi)發(fā)環(huán)境搭建教程
這篇文章主要為大家詳細(xì)介紹了.Net Core+Angular Cli/Angular4開(kāi)發(fā)環(huán)境搭建教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
JQuery運(yùn)用ajax注冊(cè)用戶實(shí)例(后臺(tái)asp.net)
JQuery運(yùn)用ajax注冊(cè)用戶實(shí)例,其實(shí)那中后臺(tái)語(yǔ)言都是差不多的形式。2009-12-12
linq to sql中,如何解決多條件查詢問(wèn)題,答案,用表達(dá)式樹(shù)!
有個(gè)小項(xiàng)目中,用到了linq to sql,既然這樣,想必需要做多條件組合查詢了,雖然我對(duì)表達(dá)式樹(shù)的研究也只是寥寥地,但除此方法,似乎別無(wú)他法,只好硬著頭皮研究一下.2011-08-08

