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

前端 未结 21 2368
滥情空心
滥情空心 2020-11-22 05:04

I am very new to Entity Framework 6 and I want to implement stored procedures in my project. I have a stored procedure as follows:

ALTER PROCEDURE [dbo].[ins         


        
21条回答
  •  日久生厌
    2020-11-22 06:06

    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("GetResultsForCampaign @ClientId", clientIdParameter)
                    .ToList();
        }
    

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

提交回复
热议问题