EF Core 6 新功能匯總(四)
在這篇文章中,你將看到 EF Core 對(duì) SQLite、In-memory 提供者和 EF.Functions.Contains 方法的改進(jìn)。
這是 EF Core 6 新功能匯總的第四篇文章:
EF Core 6 新功能匯總(四)
1SQLite 支持 DateOnly 和 TimeOnly
在 EF Core 6.0 中,SQLite 提供者支持新的 DateOnly 和 TimeOnly 類型。它將它們存儲(chǔ)為 TEXT。
using?var context = new ExampleContext();
var query1 = context.People
.Where(p => p.Birthday < new DateOnly(2000, 1, 1))
.ToQueryString();
Console.WriteLine(query1);
// SELECT "p"."Id", "p"."Birthday", "p"."Name"
// FROM "People" AS "p"
// WHERE "p"."Birthday" < '2000-01-01'
var query2 = context.Notifications
.Where(n => n.AllowedFrom >= new TimeOnly(8, 0) && n.AllowedTo <= new TimeOnly(16, 0))
.ToQueryString();
Console.WriteLine(query2);
// SELECT "n"."Id", "n"."AllowedFrom", "n"."AllowedTo"
// FROM "Notifications" AS "n"
// WHERE("n"."AllowedFrom" >= '08:00:00') AND("n"."AllowedTo" <= '16:00:00')
class?Person
{
public?int Id { get; set; }
public?string Name { get; set; }
public DateOnly Birthday { get; set; }
}
class?Notification
{
public?int Id { get; set; }
public TimeOnly AllowedFrom { get; set; }
public TimeOnly AllowedTo { get; set; }
}
class?ExampleContext : DbContext
{
public DbSet People { get; set; }
public DbSet Notifications { get; set; }
protected?override?void?OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite(@"Data Source=Db\DateOnlyTimeOnly.db");
} 2SQLite 連接是池化的
SQLite 數(shù)據(jù)庫(kù)是一個(gè)文件。因此,在大多數(shù)情況下,創(chuàng)建一個(gè)連接是很快的。然而,打開一個(gè)加密數(shù)據(jù)庫(kù)的連接會(huì)非常慢。因此,在 EF Core 6 中,SQLite 連接現(xiàn)在是池化的,就像其他數(shù)據(jù)庫(kù)提供者一樣。
class?Person
{
public?int Id { get; set; }
public?string Name { get; set; }
}
class?ExampleContext : DbContext
{
public DbSet People { get; set; }
protected?override?void?OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=EncryptedDb.db;Mode=ReadWriteCreate;Password=password");
} 3SQLite 中的命令超時(shí)
在 EF Core 6 的 SQLite 中,支持添加 Command Timeout 命令到連接字符串中,你可以用它來指定 SQLite 的默認(rèn)超時(shí)時(shí)間。
class?Person
{
public?int Id { get; set; }
public?string Name { get; set; }
}
class?ExampleContext : DbContext
{
public DbSet People { get; set; }
// 60 seconds as the default timeout for commands created by connection
protected?override?void?OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=Test.db;Command Timeout=60");
} 4SQLite 中的保存點(diǎn)
在 EF Core 6.0 中,SQLite 支持保存點(diǎn)(Savepoints)。你可以保存、回滾和釋放保存點(diǎn)。
var dbPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\Savepoints.db"));
using?var connection = new SqliteConnection($"Data Source={dbPath}");
connection.Open();
using?var transaction = connection.BeginTransaction();
// The insert is committed to the database
using (var command = connection.CreateCommand())
{
command.CommandText = @"INSERT INTO People (Name) VALUES ('Oleg')";
command.ExecuteNonQuery();
}
transaction.Save("MySavepoint");
// The update is not commited since savepoint is rolled back before commiting the transaction
using (var command = connection.CreateCommand())
{
command.CommandText = @"UPDATE People SET Name = 'Not Oleg' WHERE Id = 1";
command.ExecuteNonQuery();
}
transaction.Rollback("MySavepoint");
transaction.Commit();5內(nèi)存數(shù)據(jù)庫(kù)驗(yàn)證必需屬性
在 EF Core 6.0 中,內(nèi)存(In-memory)數(shù)據(jù)庫(kù)驗(yàn)證了必需(In-momory)的屬性。如果你試圖保存一個(gè)實(shí)體的必需屬性值為空,就會(huì)出現(xiàn)異常。如果有必要,你可以禁用這個(gè)驗(yàn)證。
using?var context = new ExampleContext();
var blog = new Blog();
context.Blogs.Add(blog);
await context.SaveChangesAsync();
// Unhandled exception. Microsoft.EntityFrameworkCore.DbUpdateException:
// Required properties '{'Title'}' are missing for the instance of entity
// type 'Blog' with the key value '{Id: 1}'.
class?Blog
{
public?int Id { get; set; }
[Required]
public?string Title { get; set; }
}
class?ExampleContext : DbContext
{
public DbSet Blogs { get; set; }
protected?override?void?OnConfiguring(DbContextOptionsBuilder options)
=> options
.EnableSensitiveDataLogging()
.LogTo(Console.WriteLine, new[] { InMemoryEventId.ChangesSaved })
.UseInMemoryDatabase("ValidateRequiredProps");
// To disable the validation
// .UseInMemoryDatabase("ValidateRequiredProps", b => b.EnableNullChecks(false));
} 6EF.Functions.Contains 方法
在 EF Core 6.0 中,你可以使用 EF.Functions.Contains 方法來處理使用值轉(zhuǎn)換器映射的列(也可以處理二進(jìn)制列)。
using?var context = new ExampleContext();
var query = context.People
.Where(e => EF.Functions.Contains(e.FullName, "Oleg"))
.ToQueryString();
Console.WriteLine(query);
// SELECT[p].[Id], [p].[FullName]
// FROM[People] AS[p]
// WHERE CONTAINS([p].[FullName], N'Oleg')
class?Person
{
public?int Id { get; set; }
public FullName FullName { get; set; }
}
public?class?FullName
{
public?string FirstName { get; set; }
public?string LastName { get; set; }
}
class?ExampleContext : DbContext
{
public?DbSet<Person> People { get; set; }
protected?override?void?OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.Property(x => x.FullName)
.HasConversion(
v => JsonSerializer.Serialize(v, (JsonSerializerOptions)null),
v => JsonSerializer.Deserialize(v, (JsonSerializerOptions)null));
}
protected?override?void?OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFCore6Contains");
} 7結(jié)尾
本文所有代碼示例都可以在我的 GitHub 中找到:
https://github.com/okyrylchuk/dotnet6_features/tree/main/EF%20Core%206#miscellaneous-enhancements原文:bit.ly/3rlHxC9
作者:Oleg Kyrylchuk
翻譯:精致碼農(nóng)
