栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

EFCore使用MySQL

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

EFCore使用MySQL

EFCore使用SQL Server应该是鼻祖了吧,哈哈!不过使用MySQL的就比较少见了,至少官网是没有引导的。因为不是MySQL微软的东西嘛,当然推崇SQL Server了;不过MySQL相对SQL Server更为轻量一些,我们就来简单整理下吧!Model层NuGet包如下:
1、Microsoft.EntityFrameworkCore.Design
2、Microsoft.EntityFrameworkCore.Tools
3、MySql.EntityFrameworkCore
4、Microsoft.EntityFrameworkCore
5、Microsoft.EntityFrameworkCore.Relational

对了,MySQL还可以安装连接Visual Studio和.NET的组件,需要注意的是,目前直连Visual Studio的版本仅支持到Visual Studio 2017,Visual Studio 2019暂时还没有相关的组件,不过并不影响使用。

编写SysContext

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

        public DbSet Student { get; set; }

    }

编写一个实体类,做一下简单Code First验证:

public class Student
    {
        [Key]
        public string Id { get; set; }
        public string Name { get; set; }

        public string Number { get; set; }

        public string Address { get; set; }
    }

同样,Web层也NuGet相同的包!在Startup.cs进行注入:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(options=>
            {
                options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddControllersWithViews();
        }

配置appsettings.json链接字符串:

"ConnectionStrings": {
    "DefaultConnection": "server=localhost;database=test;uid=root;pwd=2239Yang;"
  },

做一下,数据迁移

Add-Migration A
Update-Database

这时候打开客户端MySQL,可以看到通过自定义实体,已成功创建相应的表!

编写一个Controller简单测试下吧!

public class HomeController : Controller
    {        
        public async Task Index()
        {

            var config = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json",true,true)
                .AddInMemoryCollection()
                .Build();
            
            var connStr = config["ConnectionStrings:DefaultConnection"];

            DbContextOptions options = new DbContextOptionsBuilder().UseMySQL(connStr).Options;

            SysContext db = new SysContext(options);

            var s1 = new Student()
            {
                Id=Guid.NewGuid().ToString(),
                Name="Stu1",
                Number="Stu_No1",
                Address="BeiJing"
            };
            db.Student.Add(s1);

            var s2 = new Student()
            {
                Id = Guid.NewGuid().ToString(),
                Name = "Stu2",
                Number = "Stu_No2",
                Address = "BeiJing"
            };
            db.Student.Add(s2);

            await db.SaveChangesAsync();
            return Json(db.Student.ToList());
        }
    }

执行成功!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号