由于本人基础差,采用EF core 创建数据库时,配置数据库连接字符串时,采用了.NET 5 因此记录一下。
方式一:
配置连接字符串:
1 using Microsoft.EntityFrameworkCore; 2 using Microsoft.EntityFrameworkCore.Design; 3 4 namespace MagazineModel.Models 5 { 6 public class DesignTimeDbContextFactory: IDesignTimeDbContextFactory<MagazineContext> 7 { 8 9 public MagazineContext CreateDbContext(string[] args) 10 { 11 var builder = new DbContextOptionsBuilder<MagazineContext>(); 12 builder.UseSqlServer("Data Source=.;Initial Catalog=Magazine;User ID=XX;password=XXXXX"); 13 return new MagazineContext(builder.Options); 14 } 15 } 16 }
Context使用连接字符串
using Microsoft.EntityFrameworkCore; namespace MagazineModel.Models { public class MagazineContext : DbContext { public MagazineContext(DbContextOptions<MagazineContext> options) : base(options) { } public DbSet<Fx361Magazine> Fx361Magazines { get; set; } } }
方式二: Context 直接使用连接字符串:
using Microsoft.EntityFrameworkCore; namespace MagazineModel.Models { public class MagazineContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Data Source=.;Initial Catalog=Magazine;User ID=XX;password=XXXXX"); } public DbSet<Fx361Magazine> Fx361Magazines { get; set; } } }
两种方式皆已经测试,都可以正常连接数据库,当然建议使用第二种方式,原因是代码简洁明了。