.NetCore中EFCore for MySql

1、新建.NetCore项目

添加依赖项

Microsoft.EntityFrameworkCore.Tools
MySql.Data.EntityFrameworkCore

这里写图片描述

2、然后新建一个DbContext类。

    public class DBContext:DbContext
    {
        public DBContext(DbContextOptions<DBContext> options)
            : base(options)
        {
        }

        public DbSet<student> student { get; set; }
        //这里也可以
        //string str = @"Data Source=;Database=;User ID=;Password=;pooling=true;CharSet=utf8;port=3306;sslmode=none";
        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
        //    optionsBuilder.UseMySQL(str);

    }

3、创建数据库映射
注意:大小写和数据库保持一致

    public class student
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
    }

4、appsettings.json里添加连接字符串

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": { "MysqlConnection": "Data Source=localhost;Database=test;User ID=root;Password=123456;pooling=true;CharSet=utf8;port=3306;sslmode=none" }
}

5、在Startup.cs文件的ConfigureServices方法添加

        public void ConfigureServices(IServiceCollection services)
        {
            //注意:一定要加 sslmode=none 
            var connection = Configuration.GetConnectionString("MysqlConnection");
            services.AddDbContext<DBContext>(options => options.UseMySQL(connection));
            services.AddMvc();
        }

6、获取集合

        private readonly DBContext _db;
        //通过.NET Core框架自动为我们做构造函数依赖注入IOC。
        public HomeController(DBContext db)
        {
            _db = db;
        }
        public ActionResult Index()
        {
           var list= _db.student.ToList();
            return View();
        }

这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值