介紹#
從 Entity Framework 5.0 開始提供了 ToQueryString()
,它返回特定於 provider 的 SQL,也不需要連接到資料庫伺服器,它類似於 Entity Framework 的 ToTraceString()
。
示例#
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection()
.AddDbContext<MyDbContext>(options => options.UseSqlite());
var dbContext = services
.BuildServiceProvider()
.CreateScope()
.ServiceProvider
.GetRequiredService<MyDbContext>();
var namePrefix = "bob";
var query = dbContext.Customers.Where(x => x.Name.StartsWith(namePrefix));
var sql = query.ToQueryString();
Console.WriteLine(sql);
Console.ReadKey();
record Customer(int Id, string Name);
class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
public DbSet<Customer> Customers { get; set; }
}
輸出結果: