1. 程式人生 > >(Entity Framework Core入門)二、EFCore數據庫配置生成

(Entity Framework Core入門)二、EFCore數據庫配置生成

model res ise runtime 準備 cookie bili request data

延續上一章節https://www.cnblogs.com/dzw159/p/10646368.html

我們準備將按照AspCore的依賴註入機制獲取appsettings.json的數據庫參數配置,用以生成數據庫(代碼先行,appsettings.json的字符串獲取,前面記錄:https://www.cnblogs.com/dzw159/p/10591238.html)

創建的結構目錄如下:

技術分享圖片

1)建立項目AspEFCore、類庫(

AspEFCore.Data-引用 NuGet包:Microsoft.EntityFrameworkCore.SqlServer、

引用項目:AspEFCore.Domain

AspEFCore.Domain)

2)在 AspEFCore.Domain 創建類(City.cs、Provnce.cs)

using System;
using System.Collections.Generic;
using System.Text;

namespace AspEFCore.Domain.Model
{
    /// <summary>
    /// 城市
    /// </summary>
    public class City
    {
        /// <summary>
        /// 編碼
        
/// </summary> public int Id { get; set; } /// <summary> /// 城市名稱 /// </summary> public string Name { get; set; } /// <summary> /// 郵編 /// </summary> public string AreaCode { get; set; } /// <summary>
/// 所屬省份編碼 /// </summary> public int ProviedId { get; set; } /// <summary> /// 省份 /// </summary> public Province Province { get; set; } } }
using System;
using System.Collections.Generic;
using System.Text;

namespace AspEFCore.Domain.Model
{
    /// <summary>
    /// 省份
    /// </summary>
    public class Province
    {
        public Province()
        {
            Cities = new List<City>();
        }

        /// <summary>
        /// 編碼
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 省份名稱
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 人口
        /// </summary>
        public int Population { get; set; }

        /// <summary>
        /// 城市
        /// </summary>
        public List<City> Cities { get; set; }

    }
}

3)在 AspEFCore.Data 創建 數據連接文件 MyContext.cs

using AspEFCore.Domain.Model;
using Microsoft.EntityFrameworkCore;

namespace AspEFCore.Data
{
    public class MyContext:DbContext
    {
        /// <summary>
        /// 外部參數
        /// </summary>
        /// <param name="options">外部傳入的配置參數(這樣子的話,我們就可以通過外部來控制傳入的參數值,用以決定使用哪個數據庫)</param>
        public MyContext(DbContextOptions<MyContext> options):base(options)
        {

        }

        public DbSet<City> Cities { get; set; }
        public DbSet<Province> Provinces { get; set; }

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    //使用本地的Windows驗證
        //    optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=EFCoreDemo;Trusted_Connection=True;");
        //    //base.OnConfiguring(optionsBuilder);
        //}

    }
}

4)創建 AspEFCore.Web(引用項目AspEFCore.Domain、AspEFCore.Data)

5)在 AspEFCore.Web 創建 外部數據庫參數配置文件 appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Debug"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=AspEFCoreDemo;Trusted_Connection=True;"
  }
}

5)修改 AspEFCore.Web 的 Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspEFCore.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AspEFCore.Web
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // 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)
        {
            services.Configure<CookiePolicyOptions>(options => 
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);

            services.AddDbContext<MyContext>(
                options=>
                {
                    //獲取數據連接串
                    //options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=AspEFCoreDemo;Trusted_Connection=True;");
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                });

        }

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

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

6)使用 程序包管理控制臺 生成數據(參照https://www.cnblogs.com/dzw159/p/10646368.html 的 第5點)

註:

1)默認項目設置成 數據Data連接(MyContext.cs) 的所在項目,將數據庫配置的(AspEFCore.Web)項目設置成啟動項

2)碰到一個問題,前面在AspEFCore.Data 中引用的Microsoft.EntityFrameworkCore.SqlServer 版本為2.2.4,後AspEFCore.Web 裏面默認有引用這個(創建項目默認引用,但是版本為2.1.1),導致版本不符合,我就將AspEFCore.Data 的Microsoft.EntityFrameworkCore.SqlServer 降成版本2.1.1

技術分享圖片

感謝:Dave

地址鏈接:https://v.qq.com/x/page/a076312m3yf.html

(Entity Framework Core入門)二、EFCore數據庫配置生成