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


延續上一章節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

 

7)主鍵關聯操作

①例如:添加一個公司和城市的關聯類CityCompany.cs

 

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

namespace AspEFCore.Domain.Model
{
    public class CityCompany
    {

        /// <summary>
        /// 城市Id
        /// </summary>
        public int CityId { get; set; }

        /// <summary>
        /// 導航屬性
        /// </summary>
        public City City { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int CompanyId { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public Company Company { get; set; }
    }
}

 

②修改和添加類

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; }

        public List<CityCompany> CityCompanies{ get; set; }

        public Mayor Mayor { get; set; }

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

namespace AspEFCore.Domain.Model
{
    /// <summary>
    /// 公司
    /// </summary>
    public class Company
    {

        public Company()
        {
            CityCompanies = new List<CityCompany>();
        }

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

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

        /// <summary>
        /// 成立時間
        /// </summary>
        public DateTime EstablishDate { get; set; }

        /// <summary>
        /// 法人
        /// </summary>
        public string LegalPerson { get; set; }

        public List<CityCompany> CityCompanies { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace AspEFCore.Domain.Model
{
    public enum Gender
    {
        /// <summary>
        ////// </summary>
        Female = 0,

        /// <summary>
        ////// </summary>
        Male = 1
    }
}

 

③到Data里的OnModelCreating進行關聯(添加紅色部分,明確配置關系)

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)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

        //添加數據
        //modelBuilder.Entity<Province>().HasData(
        // new Province
        // {
        // Id = 20,
        // Name = "福建省",
        // Population = 6000
        // }
        // );

            modelBuilder.Entity<City>()
                .HasOne(x => x.Province).WithMany(x => x.Cities)
                .HasForeignKey(x => x.ProviedId);

            //配置聯合主鍵
            modelBuilder.Entity<CityCompany>()
                .HasKey(x => new { x.CityId, x.CompanyId }); 
            modelBuilder.Entity<CityCompany>()
                .HasOne(x => x.City).WithMany(x => x.CityCompanies).HasForeignKey(x=>x.CityId);

            modelBuilder.Entity<CityCompany>()
                .HasOne(x => x.Company).WithMany(x => x.CityCompanies).HasForeignKey(x => x.CompanyId);

            modelBuilder.Entity<Mayor>()
                .HasOne(x => x.City).WithOne(x => x.Mayor).HasForeignKey<Mayor>(x => x.CityId);
        }

        public DbSet<City> Cities { get; set; }
        public DbSet<Province> Provinces { get; set; }
        public DbSet<CityCompany> CityCompanies { get; set; }
        public DbSet<Company> Companies { get; set; }
        public DbSet<Mayor> Mayors { get; set; }

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

    }
}

 

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; }

    }
}

 

 

④使用程序包管理器控制台(參照上面選擇AspEFCore.Data)

1.執行  add-migration aspercore2 生成數據庫執行文件

 

2.執行Update-Database對數據庫進行更新操作

 

 

 感謝:Dave

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM