1. 程式人生 > 其它 >根據程式碼生成資料庫(基於.Net5)

根據程式碼生成資料庫(基於.Net5)

一、引入名稱空間

建立專案後,先引入名稱空間,建立兩個資料夾(Infrastructure和Models)

Startup的程式碼如下

   public class Startup
    { 
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddSession();


            services.AddDbContextPool<AppDbContext>(
                options => options.UseSqlServer("server=.; database=TestDB;Trusted_Connection=true")//Configuration.GetConnectionString())
                );
             
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            app.UseSession();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }

  

二、建立類

建立Student類,程式碼如下

 public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

  

建立AppDbContext類,程式碼如下

  public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {

        }

        public DbSet<Student> Student { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<Student>().HasData(
                new Student
                {
                    Email = "[email protected]",
                    Id = 1,
                    Name = "Name"
                }
                );
            ;

        }
    }

  

三、修改配置檔案appsettings.json

增加節點:

"ConnectionStrings": {
"DBConnectiong": "server=.; database=TestDB;Trusted_Connection=true"
},

說明:server=.; database=TestDB;Trusted_Connection=true 是連結資料庫的字串;TestDB是資料庫的名稱;

四、進入控制檯

輸入命令:Add-Migration InitialCreate

再輸入命令:Update-Database

結果如下圖所示:

來檢視一下資料庫:

資料庫建立完成;