How to call Stored Procedure in Entity Framework 6 (Code-First)?

All you have to do is create an object that has the same property names as the results returned by the stored procedure. For the following stored procedure:

    CREATE PROCEDURE [dbo].[GetResultsForCampaign]  
    @ClientId int   
    AS
    BEGIN
    SET NOCOUNT ON;

    SELECT AgeGroup, Gender, Payout
    FROM IntegrationResult
    WHERE ClientId = @ClientId
    END

create a class that looks like:

    public class ResultForCampaign
    {
        public string AgeGroup { get; set; }

        public string Gender { get; set; }

        public decimal Payout { get; set; }
    }

and then call the procedure by doing the following:

    using(var context = new DatabaseContext())
    {
            var clientIdParameter = new SqlParameter("@ClientId", 4);

            var result = context.Database
                .SqlQuery<ResultForCampaign>("GetResultsForCampaign @ClientId", clientIdParameter)
                .ToList();
    }

The result will contain a list of ResultForCampaign objects. You can call SqlQuery using as many parameters as needed.

Leave a Comment