一、前言
连接 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)、实验截图