Does Entity Framework Code First Support Stored Procedures

Does Entity Framework Code First support stored procedures?

EDIT: My original answer for EF4.1 (below) is now out of date. Please see the answer below from Diego Vega (who works on the EF team at Microsoft)!


@gsharp and Shawn Mclean: Where are you getting this information? Don't you still have access to the underlying ObjectContext?

IEnumerable<Customer> customers = 
((IObjectContextAdapter)this)
.ObjectContext.ExecuteStoreQuery<Customer>("select * from customers");

Replace the "select" statement with a stored proc, and there you go.

As for your other question: Yes, unfortunately your s.p.'s will get clobbered. You may need to add the "CREATE PROCEDURE" statements in your code.

For EF 4.2:

var customers = context.Database.SqlQuery<Customer>("select * from customers")

How to create a stored procedure from EF Core code first approach?

Under normal circumstances, we use MigrationBuilder.Sql method in the Up method of your migration class to create a stored procedure, like below:

public partial class SPCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
//...

var sp = @"CREATE PROCEDURE [dbo].[GetStudents]
AS
BEGIN
select * from Students
END";

migrationBuilder.Sql(sp);
}

protected override void Down(MigrationBuilder migrationBuilder)
{
//...
}
}

To execute a stored procedure, you can call FromSqlRaw method, like this:

var students= _dbcontext.Students.FromSqlRaw("EXECUTE GetStudents").ToList();

Call stored procedure from Entity Framework 6.1.3 code-first

Use without exec :

using (Model1 ent = new Models.Model1())
{
var regionID= new SqlParameter("@RegionID", 100);
var regionDesc= new SqlParameter("@RegionDesc", "Nima");

ent.Database.SqlQuery<Region>("InsertRegion @RegionID ,@RegionDesc", regionID ,regionDesc);
}

but in your sp not returning any recored so you can use this also :

using (Model1 ent = new Models.Model1())
{
var regionID= new SqlParameter("@RegionID", 100);
var regionDesc= new SqlParameter("@RegionDesc", "Nima");

ent.Database.ExecuteSqlCommand("InsertRegion @RegionID ,@RegionDesc", regionID ,regionDesc);
}

Entity Framework doesn't support stored procedures which build result sets from Dynamic queries or Temporary tables

found the answer here: EF4 - The selected stored procedure returns no columns

"EF doesn't support importing stored procedures which build result set from:
Dynamic queries
Temporary tables
The reason is that to import the procedure EF must execute it."



Related Topics



Leave a reply



Submit