asp.net core EF code first

 

以连接mysql数据库为例

一 安装组件

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Relational

Microsoft.EntityFrameworkCore.Tools

MySqlConnector

Pomelo.EntityFrameworkCore.MySql

 

二 新增MySQLDbContext,继承自DbContext,并新增一个数据库表实体Article

  [Table("Articles")]
    public class Article
    {
        /// 
        /// 主键id
        /// 
        [Key]
        public string Id { get; set; }

        /// 
        /// 标题
        /// 
        public string Title { get; set; }

        /// 
        /// 内容
        /// 
        [MaxLength(255)]
        public string Content { get; set; }

        /// 
        /// 创建时间
        /// 
        public DateTime CreatedDT { get; set; }

        /// 
        /// 修改时间
        /// 
        public DateTime ModifiedDT { get; set; }
    }


    public class MySQLDbContext : DbContext
    {
        public MySQLDbContext(DbContextOptions options) : base(options) { }

        public DbSet
ArticleSets { get; set; } //... }

  

三 appsettings配置数据库连接字符串,并在Startup.cs中添加服务

 

 Startup.cs:

services.AddDbContext(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(this IWebHost host) where TContext : DbContext
2 {
3     using (var scope = host.Services.CreateScope())
4     {
5       var context = scope.ServiceProvider.GetService();
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()  //调用扩展方法
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         /// 
13         /// 新增文章
14         /// 
15         /// 
16         /// 
17         /// 
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         /// 
37         /// 根据id查询文章
38         /// 
39         /// 
40         /// 
41         [AllowAnonymous]
42         [HttpGet]
43         [Route("{id}")]
44         public async Task
GetById(string id) 45 { 46 var data = await _dbContext.ArticleSets.FindAsync(id); 47 return data; 48 } 49 50 /// 51 /// 更新文章标题 52 /// 53 /// 54 /// 55 /// 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 /// 74 /// 根据id删除文章 75 /// 76 /// 77 /// 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

 

转载于:https://www.cnblogs.com/miaosha5s/p/11341957.html

你可能感兴趣的:(asp.net core EF code first)