使用net core3.1操作数据库

使用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值