欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net core EF code first

程序员文章站 2022-04-09 21:32:19
以连接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中添加服务

asp.net core EF code first

 

 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     }