2. C# .net EF

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 key

reference: EF Core tools reference (.NET CLI) - EF Core | Microsoft Learn

为DbContext和数据库的实体类型生成代码。简单说,有了实体之后可以通过代码实现数据库的创建以及迁移。

1. Setup

环境说一下:

ToolVersion
VS code...
.Net SDK6.0.403
OSMac 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();

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值