You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core中获取单个字符串值的更简便实现方法?

简化获取@@SERVERNAME的方法

EF Core 7及以上版本

EF Core 7新增了直接查询标量类型的支持,无需创建额外实体类,直接通过Database.SqlQuery<T>即可实现:

// 使用处直接执行
ServerName = await WHContext.Database.SqlQuery<string>("SELECT @@SERVERNAME").FirstAsync();

EF Core 6及以下版本

如果项目仍使用低版本EF Core,可以跳过EF实体映射,直接用ADO.NET原生方式查询:

await using var connection = WHContext.Database.GetDbConnection();
await connection.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = "SELECT @@SERVERNAME";
ServerName = (string)await command.ExecuteScalarAsync();

补充说明

你之前尝试用String替代EntityString报错,是因为EF Core 7之前的版本不支持直接从FromSqlRaw返回标量类型,必须映射到实体(包括无键实体)。上述方案针对不同版本简化了操作,无需额外定义实体类。

内容的提问来源于stack exchange,提问作者M.M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:32:33