冯 海

一个程序新人菜鸟的日记,希望大家多多关照。QQ:32316131

.net core3.1 使用EF 连接sqlserver,并codefirst 数据库

一、新建项目

二、安装必须的nuget包

 

 

三、新建几个实体模型

1.我建了一  DAL文件夹,新建上下文FonourDBContext.cs

 using Microsoft.EntityFrameworkCore;

 namespace Domain
 {
      public class FonourDBContext: DbContext
      {
          public FonourDBContext(DbContextOptions<FonourDBContext> options)
              : base(options)
          {
        }

public DbSet<Department> Departments { get; set; }
public DbSet<Menu> Menus { get; set; }
public DbSet<Role> Roles { get; set; }



protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } } }

  2.建立几个Departments等的实体

3.Startup.cs 修改 ConfigureServices(IServiceCollection services) 方法,增加对EF的支持(黄色高亮):

 

// This method gets called by the runtime. Use this method to add services to the container.
 2         public void ConfigureServices(IServiceCollection services)
 3         {
 4             // Add framework services.
 5             services.AddApplicationInsightsTelemetry(Configuration);
 6 
 7             services.AddDbContext<ApplicationDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
 8 
 9             services.AddMvc();
10 
11         }

 4.上面的 SqlServerConnection 是我们的数据库连接字符串,它的配置在 \src\appsettings.json 文件中(这个名字让我们想起了appsetting.config): 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SqlServerConnection": "Server=.;Data Source=(local);uid=sa;pwd=js123456;DataBase=myDataBase;"
  }
}

  三。在控制台使用

 使用CodeFirst数据库迁移命令创建数据库

Add-Migration Init
Update-Database

  

 

posted @ 2020-01-08 14:35  秋天来了哟  阅读(2575)  评论(0编辑  收藏  举报
认识就是缘份,愿天下人都快乐!
QQ: 32316131
Email: 32316131@qq.com