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?
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.
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.
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.
.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(); }
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With