.net core 3.1连接mysql

连接方式和2.0类似,但感觉更简便了一些

首先下载驱动, nuget 

以前都是   .core现在放到一块了,估计以后合并成.net5就会统一去掉了

需要在 startup.cs上添加如下两行代码 :

public void ConfigureServices(IServiceCollection services)

        {

            services.AddControllersWithViews();

            services.AddDbContext<DatabaseContext>(options =>

                options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        }

分别代表连接 MySQL和启用MVC模式,上面DatabaseContext,是新建的Context类,代码如下:

public class DatabaseContext : DbContext

    {

        public DatabaseContext(DbContextOptions<DatabaseContext> options)

            : base(options)

        {

        }

        protected override void OnModelCreating(ModelBuilder builder)

        {

            base.OnModelCreating(builder);

            // Customize the ASP.NET Identity model and override the defaults if needed.

            // For example, you can rename the ASP.NET Identity table names and more.

            // Add your customizations after calling base.OnModelCreating(builder);

        }

        public DbSet<News> News { get; set; }

    }

以上基本可以测试连接数据库了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容