.net core 鏈接數據庫(經過數據庫生成Modell)

建立數據庫

(掃盲貼還勞煩大神們勿噴,謝謝)web

打開數據庫 輸入以下代碼 建立數據庫sql

CREATE DATABASE [Blogging];
GO

USE [Blogging];
GO

CREATE TABLE [Blog] (
    [BlogId] int NOT NULL IDENTITY,
    [Url] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId])
);
GO

CREATE TABLE [Post] (
    [PostId] int NOT NULL IDENTITY,
    [BlogId] int NOT NULL,
    [Content] nvarchar(max),
    [Title] nvarchar(max),
    CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]),
    CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE
);
GO

INSERT INTO [Blog] (Url) VALUES
('http://blogs.msdn.com/dotnet'),
('http://blogs.msdn.com/webdev'),
('https://www.cnblogs.com/Extnet/')
GO

 

添加所須要DLL

「工具」>「NuGet 包管理器」>「包管理器控制檯」
Install-Package Microsoft.EntityFrameworkCore.SqlServer //咱們將使用一些 Entity Framework Tools 從數據庫建立模型。 所以,咱們也會安裝此工具包:
Install
-Package Microsoft.EntityFrameworkCore.Tools
咱們稍後將使用一些 ASP.NET Core 基架工具來建立控制器和視圖。 所以,咱們也會安裝此設計包: Install
-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

 

逆向生成數據庫模型

Scaffold-DbContext "Server=.;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
//輸出目錄 -OutputDir Models
//選中的table -Tables Blog,Post
若是收到錯誤 The term 'Scaffold-DbContext' is not recognized as the name of a cmdlet 請關閉並從新打開 Visual Studio。
若是收到錯誤 Build failed.  請查看一下錯誤列表,通常從新生成一下再運行上面的命令就ok了。
 

在 Startup.cs 中註冊並配置上下文

  • 刪除dbcontext中的OnConfiguring方法
  • 打開Stratup.cs
  • 而且引用如下DLL
  • using 你的類庫名.Models;
  • using Microsoft.EntityFrameworkCore;
  • 修改Stratup.cs 中的 以下內容而且將DbContext注入到上下文管道中
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc();

            var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
        }

建立一個基於Model的controller

 

 

數據庫鏈接字符串放入配置文件中

打開appsettings.json數據庫

添加ConnectionStringsjson

例子以下:app

{
  "ConnectionStrings": {
    "DefaultConnection": "server=.;uid=sa;pwd=*********;Database=******;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

 

打開Startup.cs工具

    輸入如下代碼
  • using Microsoft.Extensions.Configuration;
  • using Microsoft.Extensions.DependencyInjection;

添加configuration的依賴注入ui

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

jspa

將這部分代碼:設計

   public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc();

            var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
            services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
        }

  修改成:code

   public void ConfigureServices(IServiceCollection services)
        {

            services.AddMvc();

            var connection =  Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
        }

  

好了,經過appsettings.json獲取數據庫鏈接到這裏就ok了。

還須要什麼玩意的!麻煩點個贊而後留個言!中不中!?

參考文獻

https://docs.microsoft.com/zh-cn/ef/core/get-started/aspnetcore/existing-db 微軟官方

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1 依賴注入

 

後記

建立了一個QQ羣但願有志之士能夠加一下 點擊連接加入羣聊【.Net Core研究團】:https://jq.qq.com/?_wv=1027&k=5298dNv

相關文章
相關標籤/搜索