当前位置: 移动技术网 > IT编程>开发语言>.net > .netCore3.1连接MySql

.netCore3.1连接MySql

2020年04月13日  | 移动技术网IT编程  | 我要评论

乌尼思,今日扬州天气,解码关公

1. 创建新项目-asp.net core web 应用程序

2. 

 

 

 

3. 右键项目-管理 nuget 程序包(n)...

4. 搜索  pomelo.entityframeworkcore.mysql  安装

5. 在appsettings.json文件添加 数据库连接字符串

"allowedhosts": "*",

"connectionstrings": {

"mysqlconnection": "data source=192.168.199.999;database=gf;user id=root;password=123456;pooling=true;port=3306;sslmode=none;charset=utf8;"
}

 

6. 添加一个model

[table("flash_map2")] //特性,标记为mysql数据库中的具体表名
public class mapflash
{
[key] //特性,标记为主键
public int id_no { get; set; }
public string flash_name { get; set; }
}

7. 添加mysqldbcontext类,用来连接数据库

public class mysqldbcontext: dbcontext
    {
        public mysqldbcontext(dbcontextoptions<mysqldbcontext> options) : base(options)
        {

        }       

        public dbset<mapflash> flash_map23 { get; set; }
    }

8.  在startup类的configureservices的方法中注入一下

 public void configureservices(iservicecollection services)
        {
            services.addcontrollerswithviews();
            services.addmvc();
            services.addscoped<dbcontext, mysqldbcontext>();
            var connection = configuration.getconnectionstring("mysqlconnection");
            services.adddbcontext<mysqldbcontext>(options => options.usemysql(connection));
        }

9. 到这一步就完成全部配置了,然后可以使用了

10. 创建一个控制器,使用一下

    public class testcontroller : controller
    {
        private dbcontext dbcontext;

        public testcontroller(dbcontext _dbcontext)
        {
            this.dbcontext = _dbcontext;
        }
        public iactionresult index()
        {
          var data =  dbcontext.set<mapflash>().find(37);
            viewdata["aa"] = data.flash_name;
            return view();
        }
    }

11. 添加视图-右键上面代码中的 index 添加视图

  

@{
    viewdata["title"] = "index";
}

<h1>index</h1>
<div>
    @viewdata["aa"]
</div>

12. 运行查看结果

 

 

 

 

13. 完成

14. 如有其他疑问请在评论区留言

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网