这里写自定义目录标题
使用net core3.1操作数据库
需要安装的包
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1" />
</ItemGroup>
startup.cs
public IConfiguration configurate { get; }
public Startup(IConfiguration conf)
{
configurate = conf;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// 添加 EntityFramework服务,并使用 SQLServer 服务,mDbContext 放到文件夹Models
services.AddEntityFrameworkSqlServer().
AddDbContext<mDbContext>(option => option.UseSqlServer(configurate["database:connection"]));
services.Configure<AppsettingOptions>(configurate);
services.AddMvc();
}
- mDbContext.cs
public class mDbContext : IdentityDbContext<ApplicationUser>
{
public mDbContext (DbContextOptions<mDbContext > options) : base(options)
{
}
public virtual DbSet<Student> Student{ get; set; }
}
- ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public DateTime RegisterTime { get; set; }
}
- appsettings.json
{
"database:connection": "Data Source=.;Initial Catalog=test;User ID=sa;Password=123"
}
生成数据库
在解决方案里添加
<ItemGroup>
// 如果有这个就不需要添加
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
</ItemGroup>
- 在项目根目录(bin 文件夹同级),打开 powershell 窗口(快捷方式 shift+鼠标右键)
//执行命令
dotnet ef migrations add v1(这个是标记或此次执行的命名)
// 更新数据库
dotnet ef database update