What is dotnet ef?
Generates code for a
DbContext
and entity types for a database. In order for this command to generate an entity type, the database table must have a primary keyreference: EF Core tools reference (.NET CLI) - EF Core | Microsoft Learn
为DbContext和数据库的实体类型生成代码。简单说,有了实体之后可以通过代码实现数据库的创建以及迁移。
1. Setup
环境说一下:
Tool | Version |
VS code | ... |
.Net SDK | 6.0.403 |
OS | Mac os 12.4 Darwin |
Microsoft.AspNetCore.App Microsoft.NETCore.App | 6.0.11 |
检查是否安装了dotnet ef工具
ChensMacbook@ dotnet tool list --global
Package Id Version Commands
--------------------------------------
dotnet-ef 7.0.0 dotnet-ef
安装最新的dotnet ef 工具
dotnet tool install --global dotnet-ef
可以删除
dotnet tool uninstall --global dotnet ef
使用过程中:安装需要sqlite/sqlserve都可以通过现有的 nuget 在ide中选择安装 (vscode YYDS)
开始
1. 首先要在domain中创建一个Entity
namespace Domain
{
public class Activity
{
public Guid Id { get; set; }
public String Title { get; set; }
public DateTime Date { get; set; }
public String Description { get; set; }
public String Category { get; set; }
public String City { get; set; }
public String Venue { get; set; }
}
}
我们在实体当中插入了一个Id,这个Id会默认为将来数据库所使用的Primiary Key。换了除了Id以外的任何一个字段都不好使。除非你加入一个[Key]
[Key] //identify this is a primary key
public int userId{ get ; set ; }
2. 需要创建一个DBcontext上下文类
什么是DBcontext (usage: DbContext Class (System.Data.Entity) | Microsoft Learn)
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
refernece: DbContext Class (System.Data.Entity) | Microsoft Learn
简单来说,DBcontext是实体类和数据库之间的桥梁。
这个时候,我们可以创建一个Activity的constructor。
namespace Persistence
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base (options){}
public DbSet<Activity> Activities { get; set; }
}
}
3. 数据库的迁移
//.net 6 at program.cs
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;
builder.Services.AddDbContext<DataContext>(opt => {opt.UseSqlite(configuration.GetConnectionString("DefaultConnection")); });
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<DataContext>();
await context.Database.MigrateAsync();
await Seed.SeedData(context);
}
catch(Exception ex){
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occured during the database migration");
}
}
await app.RunAsync();