以连接mysql数据库为例 一 安装组件 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Relational Microsoft.EntityFrameworkCore.Tools MySqlConnector Pomelo.EntityFrameworkCore.MySql 二 新增MySQLDbContext,继承自DbCo
以连接mysql数据库为例
一 安装组件
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.Tools
MySqlConnector
Pomelo.EntityFrameworkCore.MySql
二 新增MySQLDbContext,继承自DbContext,并新增一个数据库表实体Article
[Table("Articles")] public class Article { /// <summary> /// 主键id /// </summary> [Key] public string Id { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 内容 /// </summary> [MaxLength(255)] public string Content { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreatedDT { get; set; } /// <summary> /// 修改时间 /// </summary> public DateTime ModifiedDT { get; set; } } public class MySQLDbContext : DbContext { public MySQLDbContext(DbContextOptions<MySQLDbContext> options) : base(options) { } public DbSet<Article> ArticleSets { get; set; } //... }
三 appsettings配置数据库连接字符串,并在Startup.cs中添加服务
Startup.cs:
services.AddDbContext<MySQLDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySQL")));
注:字符串连接名称"MySQL"与appsettings中配置的名称对应.
三 code first方式创建数据库
1.程序包管理控制台PM命令
1 remove-migrations 2 add-migrations my-gration 3 update-database
2.donet命令行
1 dotnet ef migrations remove 2 dotnet ef migrations add my-gration 3 dotnet ef database update
3.代码内执行创建数据库的代码(EnsureCreated)
新增DbContextExtension扩展类:
1 public static IWebHost EnsureCreatedDB<TContext>(this IWebHost host) where TContext : DbContext 2 { 3 using (var scope = host.Services.CreateScope()) 4 { 5 var context = scope.ServiceProvider.GetService<TContext>(); 6 context.Database.EnsureCreated(); 7 } 8 return host; 9 }
在Program.cs中调用该扩展方法:
1 public static void Main(string[] args) 2 { 3 CreateWebHostBuilder(args).Build() 4 .EnsureCreatedDB<MySQLDbContext>() //调用扩展方法 5 .Run(); 6 }
四 使用EF进行增删改查
1 [ApiController] 2 [Route("api-hd/article")] 3 public class ArticleController : ControllerBase 4 { 5 private MySQLDbContext _dbContext; 6 7 public ArticleController(MySQLDbContext dbContext) 8 { 9 _dbContext = dbContext; 10 } 11 12 /// <summary> 13 /// 新增文章 14 /// </summary> 15 /// <param name="title"></param> 16 /// <param name="content"></param> 17 /// <returns></returns> 18 [AllowAnonymous] 19 [HttpPost] 20 [Route("")] 21 public async Task<bool> Add(string title, string content) 22 { 23 var newArticle = new Article() 24 { 25 Id = Guid.NewGuid().ToString(), 26 Title = title, 27 Content = content, 28 CreatedDT = DateTime.Now, 29 ModifiedDT = DateTime.Now, 30 }; 31 await _dbContext.AddAsync(newArticle); 32 await _dbContext.SaveChangesAsync(); 33 return true; 34 } 35 36 /// <summary> 37 /// 根据id查询文章 38 /// </summary> 39 /// <param name="id"></param> 40 /// <returns></returns> 41 [AllowAnonymous] 42 [HttpGet] 43 [Route("{id}")] 44 public async Task<Article> GetById(string id) 45 { 46 var data = await _dbContext.ArticleSets.FindAsync(id); 47 return data; 48 } 49 50 /// <summary> 51 /// 更新文章标题 52 /// </summary> 53 /// <param name="id"></param> 54 /// <param name="title"></param> 55 /// <returns></returns> 56 [AllowAnonymous] 57 [HttpPut] 58 [Route("")] 59 public async Task<bool> Update(string id, string title) 60 { 61 var existArticle = await _dbContext.ArticleSets.FindAsync(id); 62 if (existArticle == null) 63 { 64 return false; 65 } 66 67 existArticle.Title = title; 68 //_dbContext.Update(existArticle); 69 await _dbContext.SaveChangesAsync(); 70 return true; 71 } 72 73 /// <summary> 74 /// 根据id删除文章 75 /// </summary> 76 /// <param name="id"></param> 77 /// <returns></returns> 78 [AllowAnonymous] 79 [HttpDelete] 80 [Route("{id}")] 81 public async Task<bool> Delete(string id) 82 { 83 var existArticle = await _dbContext.ArticleSets.FindAsync(id); 84 if (existArticle == null) 85 { 86 return false; 87 } 88 89 _dbContext.Remove(existArticle); 90 await _dbContext.SaveChangesAsync(); 91 return true; 92 } 93 94 }View Code