{"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/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Relational/Extensions/RelationalQueryableExtensions.cs#L26-L62","documentation":"CreateDbCommand throws NotSupportedException with NoDbCommand when the query's executable is not an IRelationalQueryingEnumerable. This means the IQueryable was produced by a non-relational provider (in-memory, or a third-party non-relational provider) or has been wrapped in a way that hides the relational querying enumerable. The method exists to expose the DbCommand EF would execute, so a non-relational backend has nothing to return.","triggerScenarios":"Calling queryable.CreateDbCommand() on a query built against DbContextOptions.UseInMemoryDatabase, a test double, or a provider that does not implement IRelationalQueryingEnumerable. Also when LINQ operators fully evaluated client-side leave no relational enumerable behind.","commonSituations":"Test suites using InMemory provider for speed then calling CreateDbCommand for assertion; mixing provider configurations conditionally; a provider upgrade that changed the querying-enumerable type; calling CreateDbCommand on a cached or enumerated IQueryable.","solutions":["Ensure the DbContext is configured with a relational provider (UseSqlServer, UseNpgsql, UseSqlite, etc.) at runtime.","Switch integration tests to a real relational provider (UseSqlite with in-memory connection) so CreateDbCommand works.","Guard with `query.Provider is IRelationalQueryingEnumerable` or try/catch NotSupportedException when the method is optional."],"exampleFix":"// before\noptions.UseInMemoryDatabase(\"tests\");\n...\nvar cmd = db.Blogs.CreateDbCommand();\n\n// after — use SQLite in-memory for relational semantics\noptions.UseSqlite(\"DataSource=:memory:\");\nvar cmd = db.Blogs.CreateDbCommand();","handlingStrategy":"validation","validationCode":"if (query.Provider.Execute<IEnumerable>(query.Expression) is IRelationalQueryingEnumerable)\n    var cmd = query.CreateDbCommand();\nelse\n    throw new InvalidOperationException(\"Query is not relational; cannot create DbCommand.\");","typeGuard":"static bool IsRelational(IQueryable q)\n    => q.Provider.Execute<IEnumerable>(q.Expression) is IRelationalQueryingEnumerable;","tryCatchPattern":"try { var cmd = query.CreateDbCommand(); }\ncatch (NotSupportedException ex) when (ex.Message.Contains(\"non-relational\"))\n{\n    // skip DbCommand inspection in test/in-memory runs\n}","preventionTips":["Use a real relational provider (e.g. SQLite in-memory) when tests need CreateDbCommand.","Avoid InMemoryProvider for assertions about generated SQL.","Guard CreateDbCommand calls when the provider may vary by environment."],"tags":["non-relational","in-memory-provider","dbcommand","diagnostics"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}