首页 技术交流 Netcore框架下使用Efcore+mysql的codeFirst 正文

Netcore框架下使用Efcore+mysql的codeFirst

发布日期:2021年12月14日 16:58        阅读次数:757

创建好netcore的项目后,

首先第一步,需要在nuget下安装好四个包:

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Tools

Pomelo.EntityFrameworkCore.MySql

如图:


然后定义自己的数据库上下文:

using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication1.Models
{
    public class MyDbcontext:DbContext
    {
        public DbSet<Userinfo> Userinfo { get; set; }
        

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)=>
               optionsBuilder.UseMySql("server=localhost;Database=db;Uid=root;Pwd=123456;Port=3306;", new MySqlServerVersion(new Version(5, 7, 17)));


    }

    public class Userinfo
    {
         
        public int Id { get; set; }
        public string UserName { get; set; }
    }
}

  netcore中只需要输入两个命令:(这里和netframework有所区别,netframework需要第一步执行enable-migrations)

add-migration temp

update-database     

如此就生成好了:

      


微软官方文档说的很详细:https://docs.microsoft.com/zh-cn/ef/core/get-started/overview/first-app?tabs=visual-studio#prerequisites

评论:

共 0 页 0 条记录,当前为第 1 页