以連接mysql資料庫為例 一 安裝組件 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.Relational Microsoft.EntityFrameworkCore.Tools MySqlConnector Pomelo. ...
以連接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擴展類EnsureCreatedDB擴展方法:
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