如何从编译的 Linq 查询中提取 Sql 命令

发布于 2024-08-11 16:35:58 字数 1111 浏览 4 评论 0原文

在正常(未编译)的 Linq to Sql 查询中,您可以通过以下代码从 IQueryable 中提取 SQLCommand:

SqlCommand cmd = (SqlCommand)table.Context.GetCommand(query);

是否可以对编译的查询执行相同的操作?

以下代码为我提供了编译查询的委托:

        private static readonly Func<Data.DAL.Context, string, IQueryable<Word>> Query_Get =
        CompiledQuery.Compile<Data.DAL.Context, string, IQueryable<Word>>(
            (context, name) =>
                from r in context.GetTable<Word>()
                where r.Name == name
                select r); 

当我使用它生成 IQueryable 并尝试提取 SqlCommand 时,它似乎不起作用。调试代码时,我可以看到返回的 SqlCommand 有“非常”有用的 CommandText“SELECT NULL AS [EMPTY]”,

        using (var db = new Data.DAL.Context())
        {
            IQueryable<Word> query = Query_Get(db, "word");
            SqlCommand cmd = (SqlCommand)db.GetCommand(query);
            Console.WriteLine(cmd != null ? cmd.CommandText : "Command Not Found");
        }

毫无疑问,我在 google 中找不到有关此特定场景的任何内容尝试这不是一件常见的事情...

所以...有什么想法吗?

In normal (not compiled) Linq to Sql queries you can extract the SQLCommand from the IQueryable via the following code:

SqlCommand cmd = (SqlCommand)table.Context.GetCommand(query);

Is it possible to do the same for a compiled query?

The following code provides me with a delegate to a compiled query:

        private static readonly Func<Data.DAL.Context, string, IQueryable<Word>> Query_Get =
        CompiledQuery.Compile<Data.DAL.Context, string, IQueryable<Word>>(
            (context, name) =>
                from r in context.GetTable<Word>()
                where r.Name == name
                select r); 

When i use this to generate the IQueryable and attempt to extract the SqlCommand it doesn't seem to work. When debugging the code I can see that the SqlCommand returned has the 'very' useful CommandText of 'SELECT NULL AS [EMPTY]'

        using (var db = new Data.DAL.Context())
        {
            IQueryable<Word> query = Query_Get(db, "word");
            SqlCommand cmd = (SqlCommand)db.GetCommand(query);
            Console.WriteLine(cmd != null ? cmd.CommandText : "Command Not Found");
        }

I can't find anything in google about this particular scenario, as no doubt it is not a common thing to attempt...

So.... Any thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柳絮泡泡 2024-08-18 16:35:58

您可以使用 DataContext 日志:

db.Log = Console.Out; 

You could use the DataContext log:

db.Log = Console.Out; 
弱骨蛰伏 2024-08-18 16:35:58

.NET 必须有一种方法,但您可以分析 SQL Server 数据库并捕获发送到它的 SQL。您可以从 SQL Management Studio 执行此操作。

There must be a way from .NET, but you can profile your SQL Server database and capture the SQL sent to it. You can do this from SQL Management Studio.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文