c# - 如何从 .Net 核心应用程序中的 SQL 语句获取标量值?

标签 c# .net-core entity-framework-core

.Net 核心控制台应用程序(EF 核心 2.0/Sql 服务器)中的以下代码。

var sql = _context.Set<string>()
          .FromSql("select dbo.FunctionReturnVarchar({0});", id);

出现以下异常?

Cannot create a DbSet for 'string' because this type is not included in the model for the context.

是否可以不用定义字符串属性的类?

最佳答案

在这种情况下,您需要的是 ExecuteSqlCommand具有绑定(bind)输出参数的方法:

var resultParameter = new SqlParameter("@result", SqlDbType.VarChar);
resultParameter.Size = 2000; // some meaningfull value
resultParameter.Direction = ParameterDirection.Output;
_context.Database.ExecuteSqlCommand("set @result = FunctionReturnVarchar({0});", id, resultParameter);
var result = resultParameter.Value as string;

关于c# - 如何从 .Net 核心应用程序中的 SQL 语句获取标量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46163254/

相关文章:

c# - 使用 C# 更改 SQL Server 主键

c# - 如何在 C# (Winforms) 中的 DataGridView 中添加进度条列

c# - ArgumentNullException : Value cannot be null.(参数 'items')异常

sql-server - EF Core 数据库首先使用 HasNoKey

c# - 通过 EF Core 将 1.3GB CSV 文件导入 sqlite

c# - 如何防止在单元测试中自动包含导航属性

c# - C# 对象在不可访问时是否从内存中删除

c# - 如何在没有自定义类类型的情况下获取一个类的属性

c# - .net core 2.1 log4net 多环境

c# - 为什么单独的 DbContexts 在单元测试期间修改同一个 DbSet?