{"record":{"id":"9ce3b6662c612fe0","repo":"dotnet/efcore","slug":"a-dbcommand-cannot-be-created-for-a-non-relational","errorCode":null,"errorMessage":"A DbCommand cannot be created for a non-relational query.","messagePattern":"A DbCommand cannot be created for a non-relational query\\.","errorType":"exception","errorClass":"NotSupportedException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs","lineNumber":44,"sourceCode":"    ///         executed the command.\n    ///     </para>\n    ///     <para>\n    ///         Note that DbCommand is an <see cref=\"IDisposable\" /> object. The caller is responsible for disposing the returned\n    ///         command.\n    ///     </para>\n    ///     <para>\n    ///         This is only typically supported by queries generated by Entity Framework Core.\n    ///     </para>\n    ///     <para>\n    ///         See <see href=\"https://aka.ms/efcore-docs-diagnostics\">Logging, events, and diagnostics</see> for more information and examples.\n    ///     </para>\n    /// </remarks>\n    /// <param name=\"source\">The query source.</param>\n    /// <returns>The query string for debugging.</returns>\n    public static DbCommand CreateDbCommand(this IQueryable source)\n        => source.Provider.Execute<IEnumerable>(source.Expression) is IRelationalQueryingEnumerable queryingEnumerable\n            ? queryingEnumerable.CreateDbCommand()\n            : throw new NotSupportedException(RelationalStrings.NoDbCommand);\n\n    #region FromSql\n\n    /// <summary>\n    ///     Creates a LINQ query based on a raw SQL query.\n    /// </summary>\n    /// <remarks>\n    ///     <para>\n    ///         If the database provider supports composing on the supplied SQL, you can compose on top of the raw SQL query using\n    ///         LINQ operators: <c>context.Blogs.FromSqlRaw(\"SELECT * FROM Blogs\").OrderBy(b => b.Name)</c>.\n    ///     </para>\n    ///     <para>\n    ///         As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection\n    ///         attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional\n    ///         arguments. Any parameter values you supply will automatically be converted to a <see cref=\"DbParameter\" />.\n    ///     </para>\n    ///     <para>\n    ///         However, <b>never</b> pass a concatenated or interpolated string (<c>$\"\"</c>) with non-validated user-provided values","sourceCodeStart":26,"sourceCodeEnd":62,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs#L26-L62","documentation":"CreateDbCommand (RelationalQueryableExtensions.cs:44) throws NotSupportedException(RelationalStrings.NoDbCommand) when the executed query does not yield an IRelationalQueryingEnumerable. CreateDbCommand is a relational-only diagnostic API: it only works for queries that EF Core compiled through the relational pipeline. In-memory provider, in-memory compiled queries, pre-compilation, or a query that was rewritten to client-side all produce a non-relational enumerable and are rejected.","triggerScenarios":"Calling query.CreateDbCommand() when the DbContext uses the InMemory provider (or any non-relational provider), when the query was evaluated client-side, or when the IQueryable is not an EF query at all.","commonSituations":"Unit tests using UseInMemoryDatabase that call CreateDbCommand; integration-test helper that assumes a relational provider; calling CreateDbCommand on a query that EF couldn't translate and fell back to client eval; provider-agnostic library code.","solutions":["Use a real relational provider (SQL Server/SQLite/PostgreSQL) in the scenario where you need the DbCommand - InMemory cannot produce one.","Ensure the query is fully translatable so EF keeps it in the relational pipeline (avoid client-side predicates/projections).","Guard the provider before calling: check DbContext.Database.ProviderName is a relational provider, or check `context.Database.IsRelational()`.","If you only need the SQL text, use ToQueryString() which also requires a relational provider but is more explicit."],"exampleFix":"// before (with InMemory provider)\nvar cmd = context.Blogs.CreateDbCommand(); // throws NotSupportedException\n\n// after\nif (context.Database.IsRelational())\n{\n    var cmd = context.Blogs.CreateDbCommand();\n    using (cmd) { /* ... */ }\n}\n// or switch the test fixture to UseSqlite/in-memory SQLite","handlingStrategy":"type-guard","validationCode":"if (!context.Database.IsRelational())\n{\n    // CreateDbCommand is not available; fall back or skip.\n    return null;\n}\nusing var cmd = query.CreateDbCommand();","typeGuard":"static bool CanCreateDbCommand(DbContext ctx) => ctx.Database.IsRelational();","tryCatchPattern":null,"preventionTips":["Use a relational provider (Sqlite/SqlServer) in any test that exercises CreateDbCommand.","Guard with context.Database.IsRelational() before calling.","Prefer ToQueryString() when you only need the SQL text."],"tags":["relational-only","inmemory-provider","create-dbcommand","diagnostics"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}