c# - 在 EF Core 7.0 中使用 Database.SqlQuery<T> 查询自定义类型

标签 c# entity-framework entity-framework-core ef-core-7.0

最近发布的 Entity Framework Core 7.0 提供 a new DatabaseFacade.SqlQuery<T> function ,它允许直接在底层数据库上下文上运行自定义 SQL 查询。

对于自定义 SQL 查询,我当前正在使用 Dapper ,我想用 EF 的新原生 SqlQuery 替换它功能。各个查询不能轻松地表示为 LINQ,而 EF 可以将其转换为 SQL 本身。此外,它们返回不属于数据库模型一部分的结果对象。

作为说明性示例,请使用这些简单的类和 SQL 查询:

public class Book   // Mapped to database table 'books'
{
    public int Id { get; set; }
    public string Title { get; set; }

    public int AuthorId { get; set; }
    public Author Author { get; set; } // References some complex Author object

    // ...lots of other properties...
}

// Simple type for search results
public class BookSearchResult
{
    public string AuthorName { get; set; }
    public string BookTitle { get; set; }
}

// Search for books which satisfy a complex query
var books = _dbContext.Database.GetDbConnection().QueryAsync<BookSearchResult>(@"
    SELECT a.`Name` AS 'AuthorName', b.`Title` AS 'BookTitle'
    FROM `books` b
    JOIN `authors` a ON a.Id = b.AuthorId
    ...complex query...
");

我想将其替换为

var books = _dbContext.Database.SqlQuery<BookSearchResult>(@"
    ...same query...
");

现在,documentation of SqlQuery 还说明了以下内容(我添加的粗体格式):

Creates a LINQ query based on a raw SQL query, which returns a result set of a scalar type natively supported by the database provider.

也就是说,它只能/应该用于查询标量类型,但不能用于查询自定义对象。

注释中暗示可以定义一种新的默认类型映射,但我不太明白在实践中如何实现这一点(或者是否可能)。

我可以映射 DbConnection.Database.SqlQuery<T> 的结果吗?调用自定义对象?如果是这样,怎么办?

最佳答案

目前(EF Core 7)还不能。

这是一个长期以来被要求的功能,最终随 EF Core 8 SQL queries for unmapped types 一起提供。 :

Tracked by Issue #10753: Support raw SQL queries without defining an entity type for the result

Value proposition: Applications can execute more types of SQL query without dropping down to ADO.NET or using third-party libraries.

Currently SQL queries must return a type in the model or a scalar type. In EF8, we plan to allow SQL queries that directly return types that are not contained in the EF model.

关于c# - 在 EF Core 7.0 中使用 Database.SqlQuery<T> 查询自定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75667392/

相关文章:

c# - Entity Framework Core 在转换时是延迟加载

c# - 将 Guid 传递给存储过程会引发 Microsoft.Data.SqlClient.SqlException : 'Incorrect syntax near ' @Id'. '

c# - 使用 nugetpackages 加载标记器模型时出现不可恢复的错误

c# - 如何使用 X509SecurityKey 进行 Asp.Net Core JWT 验证?

c# - 在 WPF 中绘制 tile-map 的最简单方法

c# - 如何使用 Machine.Fakes (Moq) 模拟 Function<>?

c# - 使用基于 Entity Framework 一对多属性的 ObservableCollection

c# - 在 SQL Server Compact Edition 中将 Entity Framework 代码中的种子主键首先设置为 0

sql-server - EF Core Linq 中子查询的总和

c# - 如何发布带有数据库的 WPF