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

前端 未结 21 2050
滥情空心
滥情空心 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:03

    Take a look to this link that shows how works the mapping of EF 6 with Stored Procedures to make an Insert, Update and Delete: http://msdn.microsoft.com/en-us/data/dn468673

    Addition

    Here is a great example to call a stored procedure from Code First:

    Lets say you have to execute an Stored Procedure with a single parameter, and that Stored Procedure returns a set of data that match with the Entity States, so we will have this:

    var countryIso = "AR"; //Argentina
    
    var statesFromArgentina = context.Countries.SqlQuery(
                                          "dbo.GetStatesFromCountry @p0", countryIso
                                                        );
    

    Now lets say that we whant to execute another stored procedure with two parameters:

    var countryIso = "AR"; //Argentina
    var stateIso = "RN"; //Río Negro
    
    var citiesFromRioNegro = context.States.SqlQuery(
                                "dbo.GetCitiesFromState @p0, @p1", countryIso, stateIso
                              );
    

    Notice that we are using index-based naming for parameters. This is because Entity Framework will wrap these parameters up as DbParameter objects fro you to avoid any SQL injection issues.

    Hope this example helps!

提交回复
热议问题