.NetCore EFCoreによるデータベース接続


一、SQLサービス
1.エンティティークラスの作成
   public class Student
    {
        public int Id { get; set; }
        [Required]
        [Display(Name =" :")]
        public string FirstName{ get; set; }
        [Required]
        [Display(Name =" :")]
        public string  LastName { get; set; }
        [Display(Name ="    :")]
        public DateTime BirthDate { get; set; }
        [Display(Name ="  :")]
        public Gender Gender { get; set; }
    }

2.DBContextを作成する.cs
 public class DataContext:DbContext
    {
        public DataContext(DbContextOptions options):base(options)
        {
        }

        public DbSet Students { get; set; }
    }

3.appsettingを開く.json、接続文字列の追加(SqlServer)
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "server=    ;database=    ;uid=   ;pwd=  ;" 
  }
}

 
4.スタートアップをオンにします.cs
       //    
     private readonly IConfiguration Configuration; public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) {
        //
       services.AddDbContext
( options => { options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); } );      }

移行を開始します....
転載先:https://www.cnblogs.com/mi21/p/10418305.html