1.新建一个Core的Web项目
注意:选择的是2.0版本
添加依赖项
依赖项》右键》管理NuGet程序包
输入以下包名
MySql.Data.EntityFrameworkCore
然后会出现以下弹窗,点击接收即可
新建数据库上下文
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EFCoreDemo.Models { public class EFCoreDemoDbContext : DbContext { public EFCoreDemoDbContext(DbContextOptions<EFCoreDemoDbContext> options) : base(options) { } } }
新建实体类
using System;
namespace EFCoreDemo.Models
{
public class UserInfo
{
public int ID { get; set; }
public string Email { get; set; }
public string Phone { get; set; } public DateTime CreateTime { get; set; } } }
在数据库上下文中添加属性
在Startup中添加数据上下文
string ConnectionString = "Server=localhost;Port=3306;Database=EFCoreDemo; User=root;Password=root;sslmode=none;";
services.AddDbContext<EFCoreDemoDbContext>(optionsAction => optionsAction.UseMySQL(ConnectionString));
然后在程序控制台中执行命令完成数据迁移
Add-Migration Init
执行命令之后会帮我们新建一个文件夹 Migrations 用于存放数据迁移记录
更新到数据库,自动帮我们创建号数据库,数据表
执行命令
Update-Database
更新完成之后
打开数据库后会发现已经帮我们创建好数据库和数据表