Entity Framework Code-First Execute Scalar-Valued Functions

c# code-first entity-framework

Question

How do I run a scalar function first using code? The following is what I tried, however only the query itself, not the return value, is returned.

using (var dbContext = new FTTRContext())
        {

            queryResult =
                dbContext.Database.SqlQuery<string>("SELECT [dbo].[ufnGetTotalUsers] (GETDATE())").ToString();
        }
1
13
6/3/2014 1:47:06 AM

Accepted Answer

SqlQuery brings back an instance ofDbRawSqlQuery . This class is an enumerable, thus you must enumerate it either using the default LINQ operations or by usingforeach , etc..ToString() just returns the query that is will be carried out on this object. Use to attain desired outcome.Single() or .SingleAsync() .

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

This ought to produce the desired scalar string result.

Having said that, your query appears to be bad SQL. Do you simply want to retrieve the date from SQL Server? If so, the best question to ask is probablySELECT GETDATE() Once you've completed that, you might need to use.SqlQuery<DateTime>() since the value's type is not a string.

37
6/3/2014 1:50:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow