抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

DBContext 所需包:

1
2
3
4
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

program 所需包:

1
Microsoft.EntityFrameworkCore.Design

1. 写好 DBContext

  • 配置 ConnectionString
  • 配置 DbSet<>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    public class DaimuDbContext : DbContext
    {
    public readonly string connectionString;

    public DaimuDbContext() : this(null) { }

    public DaimuDbContext(string ConnectionString)
    {
    if (ConnectionString == null ||
    ConnectionString.Length == 0)
    {
    //Configuration
    connectionString = "ConnectionString";
    }
    else
    {
    connectionString = ConnectionString;
    }
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    if (optionsBuilder != null)
    {
    optionsBuilder.UseSqlServer(connectionString);
    }
    }

    public DbSet<UserInfo> UserInfo { get; set; }

    public DbSet<OrderInfo> OrderInfo { get; set; }
    }

2. 在 Startup 中注入

1
2
3
4
5
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddDbContext<DaimuDbContext>();
}

3. 打开 NuGet 命令行 , 并选择 DBContext 文件所在目录

4. 输入命令 , 生成 migration 文件

1
add-migration  <<#name#>>

5. 输入命令, 同步到数据库

1
update-database  <<#name#>>