[譯] EF 6 新特性 - 下
阿新 • • 發佈:2022-01-19
介紹
接下來我將給大家重點介紹一下.Net 6 之後的一些新的變更,文章都是來自於外國大佬的文章,我這邊進行一個翻譯,並加上一些自己的理解和解釋。
源作者連結:https://blog.okyrylchuk.dev/entity-framework-core-6-features-part-1#heading-1-unicode-attribute
正文
EF Core 中的最小 API
EF Core 6.0 擁有自己的最小 API。新的擴充套件方法註冊 DbContext 型別並在一行中提供資料庫提供程式的配置。
const string AccountKey = "[CosmosKey]"; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSqlServer<MyDbContext>(@"Server = (localdb)\mssqllocaldb; Database = MyDatabase"); // OR builder.Services.AddSqlite<MyDbContext>("Data Source=mydatabase.db"); // OR builder.Services.AddCosmos<MyDbContext>($"AccountEndpoint=https://localhost:8081/;AccountKey={AccountKey}", "MyDatabase"); var app = builder.Build(); app.Run(); class MyDbContext : DbContext { }
遷移包
EF Core 6.0 中新的 DevOps 友好功能 - 遷移包。它允許建立一個包含遷移的小型可執行檔案。您可以在 CD 中使用它。它不需要您複製原始碼或安裝 .NET SDK(僅執行時)。
命令列:
dotnet ef migrations bundle --project MigrationBundles
包管理器控制檯:
Bundle-Migration
Pre-convention Model Configuration
EF Core 6.0 引入了約定前的模型配置。它允許您為給定型別指定一次對映配置。例如,在使用值物件時,它可能會有所幫助。
public class ExampleContext : DbContext { public DbSet<Person> People { get; set; } public DbSet<Product> Products { get; set; } protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder .Properties<string>() .HaveMaxLength(500); configurationBuilder .Properties<DateTime>() .HaveConversion<long>(); configurationBuilder .Properties<decimal>() .HavePrecision(12, 2); configurationBuilder .Properties<Address>() .HaveConversion<AddressConverter>(); } } public class Product { public int Id { get; set; } public decimal Price { get; set; } } public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public Address Address { get; set; } } public class Address { public string Country { get; set; } public string Street { get; set; } public string ZipCode { get; set; } } public class AddressConverter : ValueConverter<Address, string> { public AddressConverter() : base( v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null), v => JsonSerializer.Deserialize<Address>(v, (JsonSerializerOptions)null)) { } }
編譯模型
在 EF Core 6.0 中,您可以生成已編譯的模型。當您有一個大型模型並且您的 EF Core 啟動速度很慢時,該功能才有意義。您可以使用 CLI 或包管理器控制檯來執行此操作。
public class ExampleContext : DbContext { public DbSet<Person> People { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseModel(CompiledModelsExample.ExampleContextModel.Instance) options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SparseColumns;Trusted_Connection=True;"); } } public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
命令列:
包管理器控制檯:
包管理器控制檯:
Optimize-DbContext -Context ExampleContext -OutputDir CompiledModels -Namespace CompiledModelsExample
結語
聯絡作者:加群:867095512 @MrChuJiu