.Net EF Core使用


      

nuget新增以下包(.csproj文件中新增)

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.0" />
  </ItemGroup>

然后在Models文件夹中新增实体类,比如User实体类

public class User
{
    [Key]
    [Required]
    public string code { get; set; }
    [Required]
    public string pwd { get; set; }
    [Required]
    public string name { get; set; }
}

新增操作数据库的Context

using Microsoft.EntityFrameworkCore;
public class BlogContext: DbContext
{
    public BlogContext(DbContextOptions<BlogContext> options):base(options)
    {
        //需要自动执行Migration的请注释掉
      //this.Database.Migrate();
    }
    
    public DbSet<User> User { get; set; }
}

需要在Startup.cs文件中进行相关修改

public void ConfigureServices(IServiceCollection services)
{
    //省去若干
    services.AddDbContext<BlogContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("BlogContext")));
}

 

创建Migration,在vscode中打开命令窗口,输入

#全局工具
dotnet tool install --global dotnet-ef
#新增migration
dotnet ef Migrations add userTable
#更新数据库
dotnet ef Database update