Overview
Entity Framework Core's evolution has altered how raw SQL queries with custom result mappings are handled. This article addresses the challenges of retrieving data, particularly when combining table data with results from full-text search queries, focusing on solutions for various EF Core versions.
EF Core 8 and Later
EF Core 8 and subsequent versions simplify this process. The SqlQuery
method now directly supports returning arbitrary types. This allows the use of keyless entity types and custom classes to map query results.
EF Core 3.0 and Keyless Entity Types
For EF Core 3.0, keyless entity types provide a clean solution. Define a class without a primary key using the [Keyless]
attribute or by calling HasNoKey()
.
<code class="language-csharp">[Keyless] public class SomeModel { ... } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<SomeModel>().HasNoKey(); }</code>
Execute your query using FromSqlRaw
or FromSql
:
<code class="language-csharp">var result = context.SomeModels.FromSqlRaw("YOUR SQL SCRIPT").ToList();</code>
EF Core 2.1 and Query Types
EF Core 2.1 introduced query types, offering a structured approach to mapping custom classes. Add a DbQuery<T>
property to your DbContext
and use FromSql
:
<code class="language-csharp">public DbQuery<SomeModel> SomeModels { get; set; } var result = context.SomeModels.FromSql("YOUR SQL SCRIPT").ToList();</code>
Summary
These methods effectively address the need for custom result mapping when executing raw SQL queries in Entity Framework Core, enabling flexible data retrieval, including scenarios involving full-text search results and combined data sets. Choose the approach that best suits your EF Core version. Remember to replace "YOUR SQL SCRIPT"
with your actual SQL query.
The above is the detailed content of How Can I Execute Raw SQL Queries with Custom Result Mappings in Entity Framework Core?. For more information, please follow other related articles on the PHP Chinese website!