Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get scalar value from a SQL statement in a .Net core application?

The following code in a .Net core console application (EF core 2.0/Sql server).

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

got the following exception?

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

Is it a way without defining a class with a property of string?

like image 937
ca9163d9 Avatar asked Sep 11 '17 19:09

ca9163d9


People also ask

How do I return a single value in SQL?

The Command object provides the capability to return single values using the ExecuteScalar method. The ExecuteScalar method returns, as a scalar value, the value of the first column of the first row of the result set. The following code example inserts a new value in the database using a SqlCommand.

What is use of ExecuteScalar () method?

Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.

What execute scalar returns?

DB2Command. ExecuteScalar Method. Executes the query, and returns the first column of the first row in the resultset returned by the query. Extra columns or rows are ignored.


2 Answers

.Set<TEntity>() is for entities backed by the context.

You can try a workaround

DbConnection = connection = _context.Database.GetDbConnection();

using(DbCommand cmd = connection.CreateCommand()) {

    cmd.CommandText = "select dbo.FunctionReturnVarchar(@id)";    

    cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.VarChar) { Value = id });

    if (connection.State.Equals(ConnectionState.Closed)) { connection.Open(); }

    var value = (string) await cmd.ExecuteScalarAsync();
}

if (connection.State.Equals(ConnectionState.Open)) { connection.Close(); }
like image 191
Nkosi Avatar answered Oct 02 '22 17:10

Nkosi


What you need in this scenario is the ExecuteSqlCommand method with bound output parameter:

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;
like image 42
Ivan Stoev Avatar answered Oct 02 '22 15:10

Ivan Stoev