(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)这里生成数据库需要设置Web项为启动项(含有StartUp.cs的)
2)必须在Web项目安装Design和Tool这两个Nuget包
3)程序包管理器记得选择成AspEFCore.Data(含MyContext.cs=》包含DbSet<T>)的数据层类库
4)Update的时候出现fail-build,是由于AspEFCore.Data的NuGet需要安装SqlServer包(注:.Net3.1)
1.执行 add-migration aspercore2 生成数据库执行文件
2.执行Update-Database对数据库进行更新操作
感谢:Dave
地址链接:https://v.qq.com/x/page/a076312m3yf.html