CodeFirst如何搭建Asp.NetCore2.0網(wǎng)站-創(chuàng)新互聯(lián)

這篇文章主要介紹CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

十年的云城網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時及時工作處理。成都全網(wǎng)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整云城建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)從事“云城網(wǎng)站設(shè)計”,“云城網(wǎng)站推廣”以來,每個客戶項目都認(rèn)真落實執(zhí)行。

一步步教大家如何搭建Asp.Net Core2.0網(wǎng)站,以下所有都是建立在.NETCore2.0環(huán)境已經(jīng)搭建好

右鍵解決方案>新建項目>

選擇Web>ASP.NETCoreWeb應(yīng)用程序(.NET Core)

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

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

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

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

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

其中會包含身份信息的相關(guān)實現(xiàn),比如相關(guān)實體信息(user)之類的,如果想對擴(kuò)展微軟自動的生成的用戶實體類,可在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ù)庫的AspNetUsers中就會多出WeChatId 屬性.

一:安裝引用

nugnet恢復(fù)引用失效時,可在程序包管理控制臺輸入:

dotnet restore 即可

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

會發(fā)現(xiàn)在恢復(fù)指令后在NuGet中會有一個Microsoft.VisualStudio.Web.CodeGeneration.Design的報錯,信息如下:

已使用“.NETPortable,Version=v0.0,Profile=Profile259, .NETFramework,Version=v4.6.1”而不是項目目標(biāo)框架“.NETCoreApp,Version=v2.0”還原了包“Microsoft.Composition 1.0.27”。這可能會導(dǎo)致兼容性問題

這個庫是ASP.NET Core的代碼生成工具。包含用于生成控制器和視圖的dotnet-aspnet-codegenerator命令,暫時可先卸載,不影響項目運(yùn)行.

對項目類庫的引用有以下幾種方式

1.Nuget去安裝(官網(wǎng)https://www.nuget.org/packages/)

2.右鍵依賴項點擊菜單中的添加引用

3.可在程序包管理控制臺輸入:Install-Package引用類庫名稱

4.可右鍵編輯csproj工程文件進(jìn)行添加,然后執(zhí)行dotnet restore


CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

二.創(chuàng)建實體程序集

右鍵解決方案>添加項目>

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

首先創(chuàng)建抽象類,供Entity實體繼承,主要為每個實體提供公用屬性

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 資料版號
    /// </summary>
    1607426098
    public byte[] RowVersion { get; set; }

    /// <summary>
    /// 創(chuàng)建時間
    /// </summary>
    [DataMember]
    public DateTime CreateTime { get; set; }

    /// <summary>
    /// 更新時間
    /// </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,
  }
}

添加一個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ù)層

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

添加引用

DAL層需要用到EF實體映射相關(guān)和我們自己前面定義的Entity中的UserExtend實體表,所以要添加相關(guān)引用,DotNetCore20.Entity和 Microsoft.EntityFrameworkCore.Tools

快捷鍵:Ctrl+Alt+o 打開程序包管理器輸入以下:

install-package Microsoft.EntityFrameworkCore.Tools

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

如果是網(wǎng)絡(luò)限制下載失敗,推薦把nuget鏡像改為博客園資源,方法如下:

右鍵解決方案>管理解決方案的nuget程序包.顯示如下:

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

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

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

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; }
  }
}

在此基本的實體映射相關(guān)的代碼都完畢,現(xiàn)在還有一步,就是數(shù)據(jù)庫連接字符串的配置

首先打開appsettings.json文件,在ConnectionStrings節(jié)點下增加以下

復(fù)制代碼 代碼如下:

"DotNetCoreConnection": "Server=(localdb)\\mssqllocaldb;Database=DotNetCoreDb;Trusted_Connection=True;MultipleActiveResultSets=true"

增加后如下:

{
  "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"
   }
  }
 }
}

再打開web網(wǎng)站下的Startup文件,在ConfigureServices方法中添加一下行:

//自定義數(shù)據(jù)庫連接字符串
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ù)庫連接字符串
      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)行程序,點擊登陸(只要訪問數(shù)據(jù)庫的操作都可),出現(xiàn)錯誤頁面:

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

點擊應(yīng)用遷移CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站,即自動遷移數(shù)據(jù)庫.

由于兩個數(shù)據(jù)庫,只會自動遷移關(guān)于用戶的表AspNetUsers,

所以還得VS中程序包管理器中下命令遷移.

Add-Migration firstMigration -Context DotNetCoreDbContext

以上命令執(zhí)行后再執(zhí)行以下命令:

Update-Database -ContextDotNetCoreDbContext;

然后查看數(shù)據(jù)庫會發(fā)現(xiàn)多出兩個數(shù)據(jù)庫,

以DotNetCoreDefaultDb生成的為例,會生成如下表:

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

其中AspNetUsers就中會有之前添加的WeChatId字段

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

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

CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站

這樣一個完整的Asp.NetCore2.0網(wǎng)站就初步運(yùn)行起來了

以上是“CodeFirst如何搭建Asp.Net Core2.0網(wǎng)站”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

新聞名稱:CodeFirst如何搭建Asp.NetCore2.0網(wǎng)站-創(chuàng)新互聯(lián)
文章URL:http://muchs.cn/article20/dsgejo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、企業(yè)建站網(wǎng)站設(shè)計、App設(shè)計網(wǎng)站導(dǎo)航、建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機(jī)網(wǎng)站建設(shè)