EF Code First

Code First

编写环境

VSCode,.Net Core2.1

创建工程

1
dotnet new console

添加依赖

1
2
3
dotnet add package Microsoft.EntityFrameworkCore  -v 2.1
dotnet add package Microsoft.EntityFrameworkCore.Design -v 2.1
dotnet add package Microsoft.EntityFrameworkCore.Sqlite -v 2.1

创建代码

添加数据库对应代码,数据库Provider可以通过重写DbContext.OnConfiguring和AddDbContext(在asp.net中的服务里添加,此时构造函数需要接受一个参数DbContextOptions<TContext>)来确定,下文使用第一种方法。

注意需要get和set方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Microsoft.EntityFrameworkCore;

namespace Example{
public class UserContext: DbContext{

protected override void OnConfiguring(DbContextOptionsBuilder builder){
builder.UseSqlite("Data Source=Example.db");
}
public DbSet<User> Users{get; set;}
}

public class User{
public int ID{get; set;}
public string Name{get; set;}
}
}

创建迁移

添加一个名为Install的迁移

1
dotnet ef migrations add Install

更新数据库会创建一个Example.db文件

1
dotnet ef database update