Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When LINQ isn’t enough, use raw SQL in Entity Framework Core for a database-specific query LINQ cannot express or when measurements show EF Core’s generated SQL is inadequate for your workload. Start with a parameterizing API for values, choose an API that matches the result you need, and check whether the SQL can be composed with LINQ. Raw SQL is a targeted escape hatch—not an automatic performance upgrade—and it adds maintenance work.

When should you use raw SQL in EF Core?

Consider raw SQL when a database-specific construct is not translated from LINQ, or when you have measured a meaningful performance problem and can write better SQL for the same workload. Raw SQL is not inherently faster: the result depends on your provider, schema, query, and data. Microsoft recommends checking what EF Core generates and treating handwritten SQL as a last resort because you must maintain it yourself. Microsoft’s efficient-querying guidance discusses that trade-off.

  • Use LINQ when it expresses the query clearly and EF Core translates it appropriately. EF Core has more semantic information when it builds SQL itself and may produce cleaner SQL than when composing over supplied SQL.
  • Use raw SQL for a translation gap or a measured need for database-specific SQL.
  • For reusable database logic, consider mapping a user-defined function or table-valued function so it can be called from LINQ. A database view can represent a reusable query, but it cannot accept parameters.

These are alternatives, not performance guarantees; choose based on the query’s behavior and how the logic will be maintained.

Which EF Core raw SQL API fits the result?

Need API What it returns or does
Query mapped entities DbSet.FromSql Entity instances subject to ordinary EF Core tracking and mapping rules.
Query entities with dynamically constructed SQL text DbSet.FromSqlRaw Entity instances; keep values separate from SQL text and handle dynamic construction carefully.
Query scalars or a custom CLR result shape Database.SqlQuery<T> Scalar results, and from EF Core 8, unmapped mappable CLR types.
Query scalars or custom results using dynamic SQL text Database.SqlQueryRaw<T> The raw-SQL counterpart for non-entity results.
Run a command without returning a result set Database.ExecuteSql Executes SQL and returns the number of affected rows.
Run a command with dynamically constructed SQL text Database.ExecuteSqlRaw Executes the command; take the same care with construction and parameters as for raw queries.

FromSql was introduced in EF Core 7; earlier versions use FromSqlInterpolated. EF Core 8 added SqlQuery support for unmapped mappable CLR types. Those types have no keys or relationships, so choose a mapped entity when you need entity relationships or tracking. See Microsoft’s SQL Queries documentation and EF Core 8 release documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How do you parameterize raw SQL in EF Core?

Use interpolated parameterizing APIs for values. For an entity query, the current API is FromSql:

var blogs = context.Blogs.FromSql($"SELECT * FROM dbo.Blogs WHERE Rating > {minimumRating}");

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

EF Core sends the embedded value as a parameter rather than inserting it into the SQL text. The equivalent principle applies to ExecuteSql for commands and SqlQuery<T> for non-entity results.

Use a raw variant only when you need to construct the SQL text dynamically. Keep values as separate arguments, for example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

var blogs = context.Blogs.FromSqlRaw("SELECT * FROM Blogs WHERE Rating > {0}", minimumRating);

Do not concatenate user-controlled text into executable SQL or pass an interpolated string containing unvalidated user values as the raw SQL argument. FromSqlRaw is not unsafe by itself when values are passed separately using placeholders; the hazard is unsafe construction. Microsoft’s EF Core 10 API reference warns against concatenating or interpolating unvalidated values into this API.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Parameters represent values, not SQL syntax such as table names, column names, or keywords. As a practical security measure, if an identifier must vary, select it from an allow-list of permitted identifiers and construct that syntax separately. Parameterization also does not validate business rules or authorize an input; the application must do those things.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Can you compose LINQ over a raw SQL query?

FromSql starts directly on a DbSet; it cannot be attached to an arbitrary LINQ query root. You can compose LINQ operators after the raw query, but EF Core treats the supplied SQL as a subquery. The SQL must therefore be valid in that position for the target provider.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Composable SQL generally begins with SELECT. On SQL Server, a trailing semicolon, a query-level hint, or certain ORDER BY forms can make SQL invalid as a subquery. Check the provider’s requirements when composing.

Stored procedures

Stored procedure calls are generally not composable. On SQL Server, composing a server-side operator over a stored procedure call produces invalid SQL. If client-side processing is intended, switch to client enumeration immediately after the raw call, using AsEnumerable() or AsAsyncEnumerable(); operators after that point run on the client rather than being translated into SQL. Microsoft documents this composition change in its EF Core 3.x breaking changes.

What happens to entity tracking and related data?

Entity results from raw SQL follow the same tracking rules as entity results from LINQ: they are tracked by default. For a read-only query that does not need change tracking, add AsNoTracking(). Raw SQL does not automatically load related data; you can compose Include where the SQL and provider support that composition.

The result shape must match the mapped entity. Return every mapped entity property and use result column names corresponding to the mapped database columns. If you need only a custom projection and not entity relationships or change tracking, an EF Core 8 unmapped result type may be a better fit.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision checklist

  1. Check translation first. Determine whether LINQ expresses the query and whether EF Core translates it suitably for your provider.
  2. Measure before optimizing. Establish that the generated query is a real problem under your schema and workload; do not assume handwritten SQL is faster.
  3. Choose the result model. Use FromSql for mapped entities, SqlQuery<T> for supported scalar or custom unmapped results, and ExecuteSql for commands with no result set.
  4. Parameterize values. Prefer interpolated APIs; if constructing raw SQL text, pass values separately and never splice untrusted input into executable SQL.
  5. Check composition and mapping. Ensure the SQL is valid as a subquery if LINQ follows it, and ensure entity results include all mapped columns.
  6. Account for upkeep. Keep handwritten SQL understandable and tested as the schema, provider, and application evolve; for recurring logic, assess mapped functions or a view.

For additional context on query generation and performance trade-offs, see Microsoft’s advanced performance topics.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.