Entity Framework Code-First Performing Scalar-Valued Functions

How can I execute a scalar function using code? Below I tried, but only the request itself is returned, not the return value.

using (var dbContext = new FTTRContext()) { queryResult = dbContext.Database.SqlQuery<string>("SELECT [dbo].[ufnGetTotalUsers] (GETDATE())").ToString(); } 
+7
c # entity-framework code-first
source share
1 answer

SqlQuery returns an instance of DbRawSqlQuery . This class is enumerable, and it expects you to enumerate it either using standard LINQ statements, or through foreach , etc. .ToString() on this object simply returns the request that will be executed. To get the desired result, use .Single() or .SingleAsync() .

 queryResult = dbContext.Database .SqlQuery<string>("SELECT [dbo].[ufnGetTotalUsers] (GETDATE())") .Single(); 

This should return the result of the scalar string you are looking for.

However, your query appears to be invalid SQL. Are you just trying to just get the date with SQL Server? If so, the query should be SELECT GETDATE() . As soon as you do this, you may have to use .SqlQuery<DateTime>() since the type of this value is not a string.

+29
source share

All Articles