Search code examples
asp.netasp.net-mvc-4entity-framework-6ef-code-first

How to import stored procedure using code first ASP.NET MVC and Entity Framework


I want to import a stored procedure using EF code-first, the code is created from SQL Server. I tried to check the articles posted but I seem not to find something I understand so far. The SQL statement below is 3 tables joining, so if I can get an example of how I could work around it using the sample code below.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[InvoiceReport]
AS
    SELECT 
        Ordering.order_id,
        Ordering.CustomerId,
        Ordering.invoice_number,
        Ordering.date_order_placed, 
        Customer.FirstName, 
        Customer.LastName, 
        Customer.EmailId, 
        Invoice_Line_Items.item, 
        Invoice_Line_Items.department, 
        Invoice_Line_Items.service, 
        Invoice_Line_Items.gender, 
        Invoice_Line_Items.quantity, 
        Invoice_Line_Items.price, 
        Invoice_Line_Items.pick_up_address, 
        Invoice_Line_Items.pick_up_date, 
        Invoice_Line_Items.pick_up_time, 
        Invoice_Line_Items.drop_off_address, 
        Invoice_Line_Items.drop_off_date, 
        Invoice_Line_Items.drop_off_time 
    FROM 
        Ordering 
    JOIN
        Customer ON Ordering.CustId = Customer.CustId
    JOIN
        Invoice_Line_Items ON Customer.CustId = Invoice_Line_Items.CustId

RETURN 0

Solution

  • I usually use stored procedures in the following way:

    Example migration:

    public partial class yourmigration: DbMigration
    {
        protected override void Up()
        {
            Sql("CREATE PROCEDURE SQL HERE");
        }
    
        //dont forget the down.
    }
    

    For EF 6, here's a good article about it: https://www.entityframeworktutorial.net/entityframework6/code-first-insert-update-delete-stored-procedure-mapping.aspx