EntityFrameworkCore 連線 SqlServer 資料庫
阿新 • • 發佈:2020-10-18
一、前言
連線 SqlServer 資料庫,需要的步驟:建立資料庫-》建立表-》Stratup匯入-》建立DbContext-》在Controller使用
二、程式碼實現
(1)、建立資料庫
(2)、在 Startup ConfigureServices方法中配置
services.AddDbContextPool<CommonDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
其中資料庫連線為
"ConnectionStrings": { "Default": "Server=.; Database=db.book; Trusted_Connection=False; uid=zxx; pwd=123456; MultipleActiveResultSets=true;" },
(3)、建立 Book 實體
using System.ComponentModel.DataAnnotations.Schema; namespace WebApplication1.Models { [Table("Book")] public class Book {/// <summary> /// 標識 /// </summary> public int Id { get; set; } /// <summary> /// 書名 /// </summary> public string Name { get; set; } /// <summary> /// 描述 /// </summary> public string Descrption { get; set; } } }
(4)、建立CommonDbContext ,繼承 DbContext ,並且引入 Book 類
using Microsoft.EntityFrameworkCore; using WebApplication1.Models; namespace WebApplication1 { public class CommonDbContext : DbContext { public CommonDbContext(DbContextOptions options) : base(options) { } public DbSet<Book> Books { get; set; } } }
(5)、使用 Book 獲取資料
using Microsoft.AspNetCore.Mvc; using System.Linq; using WebApplication1.Services; namespace WebApplication1.Controllers { public class BookController : Controller { // 定義介面 private readonly IBookService _bookService; private readonly CommonDbContext _commonDbContext; //注入介面 public BookController(IBookService bookService, CommonDbContext commonDbContext) { _bookService = bookService; _commonDbContext = commonDbContext; } public IActionResult Index() { //呼叫方法 var desc = _bookService.GetDescrption(); var books = _commonDbContext.Books.ToList(); return Content(books.ToString()); } } }
(6)、實驗截圖