EF Core – Get Started 搭建单侧环境
有时候想搭个环境做测试, 又记不住那些 command, 官方教程又啰嗦. git clone 模板又不太好管理, 索性记入在这里吧.
创建项目
dotnet new webapp -o SimpleTestEFCore
for console app 的话
dotnet new console -o SimpleTestEFCore
Install NuGet
dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools #(如果你要 F5 debug db.Database.Migrate(), 这个一定要装哦)
Files
Product.cs
namespace SimpleTestEFCore.Entity; public class Product { public int Id { get; set; } public string Name { get; set; } = ""; }
ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore; namespace SimpleTestEFCore.Entity; public class ApplicationDbContext : DbContext { public ApplicationDbContext( DbContextOptions<ApplicationDbContext> options ) : base(options) { } public DbSet<Product> Products => Set<Product>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>().ToTable("Product"); modelBuilder.Entity<Product>().Property(e => e.Name).HasMaxLength(256); } }
for console app 的话,不需要 constructor 不需要传 options
appsettings.json
"ConnectionStrings": {
"ApplicationDbContext": "Server=192.168.1.152;Database=SimpleTestEFCore;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
},
p.s. TrustServerCertificate=true 是 EF Core 7.0 之后才需要添加的 (算是 workaround, right way 是做 Certificate).
参考:
Github Issue – EFCore.SqlServer 6.0.1 Untrusted certificate authority error
Released: General Availability of Microsoft.Data.SqlClient 4.0
因为 EF Core 7.0 depend 了 Microsoft.Data.SqlClient 4.0 而 4.0 有一个 breaking changes Encrypt = true, by default. .
Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options => { options .UseSqlServer(builder.Configuration.GetConnectionString("ApplicationDbContext")) .LogTo(Console.WriteLine); // log sql query for easy debug });
for console app 的话,不需要 appsettings.json, 和 Program.cs 的 setup,取而代之的是在 ApplicationDbContext overrde OnConfiguring 方法
public class ApplicationDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .UseSqlServer("Server=192.168.1.152;Database=SimpleTestEFCore;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True") .LogTo(Console.WriteLine); } }
cmd
dotnet ef migrations add init
dotnet ef database update
Index.cshtml.cs
using SimpleTestEFCore.Entity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; namespace SimpleTestEFCore.Pages; public class IndexModel : PageModel { public async Task OnGetAsync([FromServices] ApplicationDbContext db) { var products = await db.Products.ToListAsync(); db.Products.Add(new Product { Name = "Product1" }); await db.SaveChangesAsync(); } }
想在 program.cs 注入也可以, 必须 CreateScope 哦.
var app = builder.Build(); using var scope = app.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); var person = new Person { Name = "Derrick", Animals = new List<Animal> { new Dog { Name = "Dog1", DogPrice = 100 }, new Cat { Name = "Cat1", CatPrice = 100 }, } }; db.People.Add(person); await db.SaveChangesAsync();
for app console 的话
using EFCore.Entity; using Microsoft.EntityFrameworkCore; using var db = new ApplicationDbContext(); var products = await db.Products.ToListAsync(); Console.WriteLine(products.Count);