asp.net core 2.1 dotnet (一) 生成DbContext

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiajing13579/article/details/82804002

# asp.net core 2.1 dotnet 生成DbContext

# 建立环境

win10+ .net core 2.1 + vscode

# 目地

.netcore 2.1 环境中使用 .net webapi 以及 Microsoft EntityFramework core 以及 看看 vscode 开发 好不好用

# 准备环境

0. .net core 2.1 安装

1. vscode 中安装 插件 OmniSharp 用来支持 c# 的语法。

2. vscode 中安装 插件 NetGut 使 vscode 中可以使用 netgut 安装包

#开始

1.新建一个目录。 d:\CoreAPI

2.在 visual studio code 中打开这个目录。

使用命令 dotnet new webapi 建立 webapi 项目

可以用 dotnet new 建立很多类型的项目 可以使用 dotnet new --help 自己查看。

3.安装包 CTRL+ SHIFT+ P 打开 vscode 的 NUGET工具,安装包

```

<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.3"/>

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.3"/>

```

安装包完成以后 就可以 在命令行使用 dotnet restore 来执行 看能否成功。

4.建一个Model文件夹,来存放我们的model 类(codeFirst )方式,

```

namespace CoreAPI.Mdoel

{

public class User

{

public int Id { get; set; }

public string UserName { get; set; }

public string Password { get; set; }

}

}

```

5.新建AppDbContext.cs 文件

```

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using Microsoft.EntityFrameworkCore;

using CoreAPI.Mdoel;

namespace CoreAPI

{

public class APPDbContext:DbContext

{

public APPDbContext(DbContextOptions<APPDbContext> options):base(options)

{

}

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

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

base.OnModelCreating(modelBuilder);

}

}

}

```

6. 在appsettings.json 文件中 加入配置文件

配置完后如下:

```

{

"ConnectionStrings": {

"SqlServerConnection": "Server=.;Database=dbCore;User ID=sa;Password=intuitive0506;"

},

"Logging": {

"LogLevel": {

"Default": "Warning"

}

},

"AllowedHosts": "*"

}

```

7.在项目的startup.cs 文件中配置 EF

```

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// 这两句话

var sqlConnection = Configuration.GetConnectionString("SqlServerConnection");

services.AddDbContext<APPDbContext>(option => option.UseSqlServer(sqlConnection));

}

```

8.加完以后就可以使用命令 dotnet ef migrations add v1 来生成一个 migrations 的目录 内部就是我们要生成的 数据库的内容,执行完后再执行 dotnet ef database update 这个时候数据库中就会多出我们mode 建的表。user了。

之后我们在打开数据库刷新下就可以看到连接的数据库和表了


 

猜你喜欢

转载自blog.csdn.net/xiajing13579/article/details/82804002