Suppose we have the following scalar function stored in the server database:

CREATE FUNCTION dbo.spTest () RETURNS INT BEGIN DECLARE @result INT; SET @result = 1; RETURN @result; END GO 

How to call this function using entity framework a and get the result?


I tried to do this:

 var cmd = _context.Database.Connection.CreateCommand(); cmd.CommandText = "[dbo].[spTest]"; if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open(); try { var result = cmd.ExecuteReader(); } catch (Exception) { throw; } 

result contains no values. based on this example

Also found the following advice

on the basis of which I tried to do this:

 var query = _context.Database .SqlQuery(typeof(int),"dbo.spTest").ToListAsync(); var downtime = (int)query.Result.Single(); 

I get the following exception:

The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types.

  • one
    You do not have a procedure, but the function I think cmd.CommandText should be SELECT [dbo].[spTest] - gofr1
  • @ gofr1 if everything were so simple, Exception: Failed to bind the composite identifier "dbo.spTest" - Bald
  • A mistake! SELECT dbo.spTest () - gofr1
  • @ gofr1 thanks for the hint. I found why the select [dbo].[Имя функции] construction did not work for me initially select [dbo].[Имя функции] . it was necessary to put the @ symbol before the beginning of the line; otherwise, I got out an error - Bald
  • @ gofr1 can publish as an answer - Bald

1 answer 1

You need to change cmd.CommandText :

 cmd.CommandText = "SELECT [dbo].[spTest] ()"; 

If the function with parameters:

 cmd.CommandText = "SELECT [dbo].[spTest](@param)";