Microsoft.EntityFrameworkCore.SqlServer:SQL server 需要添加包
Microsoft.EntityFrameworkCore.Tools
Newtonsoft.Json:用于Json格式转换


创建一个实体类来表示数据库表。在项目中创建一个名为Customer.cs的文件,并添加以下代码
- namespace AliWorkbenchProgram.Models
- {
- public class Customer
- {
-
- public int Id { get; set; }
- public string Name { get; set; }
- public string Email { get; set; }
-
-
-
- }
- }
创建一个数据库上下文类,用于定义实体类和数据库连接配置。在项目中创建一个名为AppDbContext.cs的文件,并添加以下代码:
-
- using AliWorkbenchProgram.Models;
- using Microsoft.EntityFrameworkCore;
-
-
-
- namespace AliWorkbenchProgram.DB
- {
- public class AppDbContext : DbContext
- {
-
- public AppDbContext(DbContextOptions
options ) : base(options) - {
- }
-
- public DbSet
Customers { get; set; } -
-
-
- }
- }
接下来,配置数据库连接。打开appsettings.json文件,并添加以下内容:

- {
-
- "ConnectionStrings": {
- "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
-
-
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft.AspNetCore": "Warning"
- }
- },
- "AllowedHosts": "*"
- }
然后,在Startup.cs文件的ConfigureServices方法中添加以下代码,用于配置数据库上下文的依赖注入:
创建类 DbEntitys 继承 DbContext
using Microsoft.EntityFrameworkCore;
-
- using AliWorkbenchProgram.Models;
- using Microsoft.EntityFrameworkCore;
-
-
- namespace AliWorkbenchProgram.DB
- {
- public class DbEntitys : DbContext
- {
-
- ///
- /// 配置连接字符串,每次访问数据库之前会自动执行此方法,在这里配置连接字符串
- /// 相当于连接前事件
- /// 使用 IOC 注入的方式不实现此方法
- ///
- ///
- protected override void OnConfiguring(DbContextOptionsBuilder builder)
- {
- // 连接字符串
- string ConnString = "xxx";
-
- // 连接SqlServer
- builder.UseSqlServer(ConnString);
-
- // 连接MySql
- //builder.UseMySql(ConnString,new MySqlServerVersion(new Version()));
- }
-
-
- ///
- /// 默认构造函数 使用方法与原来一样
- ///
- public DbEntitys() : base() { }
-
- ///
- /// 通过IOC
- ///
- ///
- public DbEntitys(DbContextOptions
options ) : base(options) - { }
-
-
- /*
- ///
- /// 无主键 视图
- ///
- ///
- protected override void OnModelCreating(ModelBuilder builder)
- {
- //指定主键字段,如果主键名称是id/Id/ID,可以省略
- builder.Entity
().HasKey("Key"); - //指定为无主键或视图,不然可能会报错
- builder.Entity
().HasNoKey(); - builder.Entity
().HasNoKey(); - }
- //表映射
- public virtual DbSet
Tab1 { get; set; } - public virtual DbSet
Tab2 { get; set; } - */
-
- //表映射
- public virtual DbSet
Students { get; set; } - //public virtual DbSet
Tab2 { get; set; } -
-
-
-
-
-
-
- }
- }
在 Program.cs

- // ↓↓↓↓↓ 在此范围内 ↓↓↓↓↓
-
- var ConnString = "xxx";
- //注入
- builder.Services.AddDbContext
(x => x.UseSqlServer(ConnString)); -
- // ↑↑↑↑↑ 在此范围内 ↑↑↑↑↑
在控制器 xxxController

- //
- /// 数据库操作实例
- ///
- private readonly DbEntitys _context;
-
- ///
- /// 构造函数获取实例
- ///
- ///
- public StudentController(DbEntitys db)
- {
- _context = db;
- }
-
-
- [HttpGet(Name = "GetData")]
- public IEnumerable
Get() - {
- //查询数据
- return _context.Students.ToList();
- }