创建好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