简体   繁体   中英

Cast Error in SQL Server when outputting an integer from stored procedure

I have this for a stored procedure which outputs just an integer

ALTER PROC GetPendingReservations
AS
BEGIN
    SELECT
        COUNT(DISTINCT FacilityAndAmenityId ) 
    FROM
        [Property].[PropAndAmenReservation] with(nolock)
    WHERE
        IsGranted = 'False' 
        AND CAST(StartDate AS DATE) = CAST(GetDate() AS DATE) 
        AND FacilityAndAmenityId NOT IN (SELECT FacilityAndAmenityId 
                                         FROM [Property].[PropAndAmenReservation] with(nolock)
                                         WHERE IsGranted = 'True' 
                                           AND CAST(StartDate AS DATE) = CAST(GetDate() AS DATE))
END

and I call it in my web api through this.

[HttpGet]
[Route("api/getfacilitiesreservation")]
public int GetFacilitiesReservation()
{
            using(var db = new ApplicationDbContext())
            {
                try
                {
                    const string query = "GetPendingReservations";

                    var count = db.Database.SqlQuery<int>(query);
                    return count;
                }
                catch(Exception ex)
                {
                    return 0;
                }
            }
}

But I get this error in my catch exception:

The specified cast from a materialized 'System.Int32' type to the 'System.String' type is not valid.

If I use db.Database.SqlQuery<int>(query) , this is what I get:

在此处输入图片说明

Can you please show me how to this right? Thank you.

Some things to consider in your issue:

1) SELECT COUNT() query returns a scalar integer mentioning total row count.

2) Database.SqlQuery<T> used to execute raw SQL query returns instance of DbRawSqlQuery which implements IEnumerable collection and expects iteration to get values inside it.

Based from these considerations and method return type as int , you should return single value of query result like this:

using (var db = new ApplicationDbContext())
{
    try
    {
        const string query = "GetPendingReservations";

        // First(), FirstOrDefault() or SingleOrDefault() may also be used
        return db.Database.SqlQuery<int>(query).Single();
    }
    catch (Exception ex)
    {
        // exception handling
    }
}

Similar issue: Entity Framework Code-First Execute Scalar-Valued Functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM