ASP.NET Core 資料庫連線+專案建置

ASP.NET Core 8 ,Web API ,Database First ,SqlServer ,Visual Studio 2022

專案建置到連線資料庫

1.建立測試資料庫

資料庫:NetCore8Example
資料表:Member
資料欄位:Id(主Key)自動流水號,Name中文,AttackPower數字
PS:每個資料表都要有主Key,後面執行指令才不會報錯誤
USE [NetCore8Example]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Member](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NULL,
	[AttackPower] [int] NULL,
 CONSTRAINT [PK_Member] PRIMARY KEY CLUSTERED 
(
	[Id] 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
SET IDENTITY_INSERT [dbo].[Member] ON 

INSERT [dbo].[Member] ([Id], [Name], [AttackPower]) VALUES (1, N'王大明', 81)
INSERT [dbo].[Member] ([Id], [Name], [AttackPower]) VALUES (2, N'王二明', 68)
INSERT [dbo].[Member] ([Id], [Name], [AttackPower]) VALUES (3, N'王小明', 12)
SET IDENTITY_INSERT [dbo].[Member] OFF

 

2.建立專案

專案範本
專案名稱和路徑
設定.NET 8
完成畫面

 

3.修改全球化組態設定

使用預設狀態可能再建立資料庫Model語法時出現以下錯誤
Only the invariant culture is supported in globalization-invariant mode. See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')
 en-us is an invalid culture identifier.

修改方式如下
 ([方案]下面的[專案]點兩下開啟檔案)D:\NET8\NetCore8Api\NetCore8Api.csproj
 將InvariantGlobalization修改為false
InvariantGlobalization修改為false

 

4.主控台安裝工具和建立資料庫Model

1.安裝 Microsoft.EntityFrameworkCore.SqlServer
2.安裝 Microsoft.EntityFrameworkCore.Tools
3.將資料庫格式用工具產生對應的Model
  此範例會產生兩個檔案[NetCore8ExampleContext.cs][Member.cs]

操作方法在(檢視>其他視窗>套件管理器主控台)下指令
1.  Install-Package Microsoft.EntityFrameworkCore.SqlServer
2.  Install-Package Microsoft.EntityFrameworkCore.Tools
3.  Scaffold-DbContext "Data Source=伺服器IP位置;Database=資料庫名稱;User ID=帳號;Password=密碼;TrustServerCertificate=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models  -UseDatabaseNames -NoPluralize -NoOnConfiguring -Force

 

5.設定資料庫連線

5.1.開啟appsettings.json添加連線字串
{
	... ,
	
	"ConnectionStrings": {
		"DbConnStr1": "Data Source=[伺服器IP位置];Database=[資料庫名稱];User ID=[帳號];Password=[密碼];TrustServerCertificate=true;"
	}
}
5-2.開啟Program.cs設定連線
using Microsoft.EntityFrameworkCore;

string StrDb1 = builder.Configuration.GetConnectionString("DbConnStr1");
builder.Services.AddDbContext<NetCore8ExampleContext>(o => o.UseSqlServer(StrDb1));

 

6.建立新的Controller

修改Controller資料
using Microsoft.AspNetCore.Mvc;
using NetCore8Api.Models;

namespace NetCore8Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ConnectionTestController : Controller
    {
        // 資料庫
        private readonly NetCore8ExampleContext _netCore8ExampleContext;

        // 初始化
        public ConnectionTestController(NetCore8ExampleContext netCore8ExampleContext)
        {
            _netCore8ExampleContext = netCore8ExampleContext;
        }

        // Get網頁瀏覽器可以直接讀取
        [HttpGet]
        public IActionResult Index()
        {
            var success = "";
            foreach (var item in _netCore8ExampleContext.Member)
            {
                success += item.Id + ":";
                success += item.Name;
                success += ",";
            }
            return Ok(success);
        }
    }
}

 

7.執行測試

  執行後瀏覽器輸入https://localhost:XXXX/api/ConnectionTest

 可看到資料庫內容表示連線沒問題喔~^^ 

我只是一棵樹