一、前言
連接 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)、實驗截圖