myesn

myEsn2E9

hi
github

EF Core: 用 ToQueryString() 将 LINQ 转换为 SQL

介绍#

从 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; }
}

输出结果:
image

参考#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.