简体   繁体   中英

Call Stored Procedure In Entity Framework

I am using Entity Framework to call a stored procedure. The stored procedure looks like this:

ALTER PROCEDURE [dbo].[AdminContracts] 
    @StatusId INT
AS
BEGIN
    SET NOCOUNT ON;

    SELECT .. 

and my code looks like this:

public virtual ObjectResult<AdminOrder> GetAdminOrders(int orderStatus)
{
    return ((IObjectContextAdapter) this).ObjectContext.ExecuteStoreQuery<AdminOrder>("AdminContracts", new SqlParameter("@StatusId", orderStatus));
}

which seems to be correct from the other questions on SO

However, it causes an exception:

Procedure or function 'AdminContracts' expects parameter '@StatusId', which was not supplied

Looks ok to me but obviously I am missing something

Try this code:

public virtual ObjectResult<AdminOrder> GetAdminOrders(int orderStatus)
    {
        return ((IObjectContextAdapter) this).ObjectContext.ExecuteStoreQuery<AdminOrder>("EXEC AdminContracts @StatusId", new SqlParameter("StatusId", orderStatus));
    }

ExecuteStoreQuery<T> Method Executes a query directly against the data source that returns a sequence of typed results. so it can be user to run T-SQL statement you can check its documentation so your code it will be as following:

public virtual ObjectResult<AdminOrder> GetAdminOrders(int orderStatus)
{
        return ((IObjectContextAdapter) this).ObjectContext.ExecuteStoreQuery<AdminOrder>("EXEC AdminContracts @StatusId", new SqlParameter("StatusId", orderStatus));
}

but if you want to call stored producer or function you can use ExecuteFunction<TElement> Method Executes a stored procedure or function that is defined in the data source and mapped in the conceptual model, with the specified parameters. Returns a typed ObjectResult. you can check its documentation

so your code it will be as following:

public virtual ObjectResult<AdminOrder> GetAdminOrders(int orderStatus)
{
  return ((IObjectContextAdapter) this).ObjectContext.ExecuteStoreQuery<AdminOrder>("AdminContracts", new ObjectParameter("@StatusId", orderStatus));
}

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