Is stored procedures supported by Entity Framework Code First?

c# code-first entity-framework stored-procedures

Question

I've seen EF Code First presentations before, but I haven't yet seen how EFCF integrates with stored procedures.

How can I define a method that employs some special purpose? Can I use an entity instead of manually mapping entity attributes to sp arguments when calling a function that uses sp?

What happens if I alter my model, too? Will it lose my SP if I recreate the table from the model? What about triggers, then?

Are there any future intentions to support these items if they are not already supported?

1
112
1/30/2011 9:24:25 PM

Accepted Answer

EDIT: My previous response for EF4.1 (below) is no longer valid. Please visit the following response from Diego Vega (a member of the Microsoft EF team)!


Shawn Mclean and @gsharp: What source are you using for this data? Access to the underlying ObjectContext is still available, right?

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

You may do this by substituting a stored procedure for the "select" expression.

Regarding your second inquiry: Sadly, your s.p.s will be destroyed. The "CREATE PROCEDURE" statements may need to be added to your code.

For EF 4.2:

var customers = context.Database.SqlQuery<Customer>("select * from customers")
66
5/23/2017 11:47:06 AM

Popular Answer

Update: For inserts, updates, and deletes, EF Code First does enable stored procedure mapping as of EF6. Using the MapToStoredProcedures method, you may provide a stored procedure mapping when creating a model. For such processes, we also provide automated scaffolding of fundamental stored routines. Take a look at the feature specification here.

Original response In the first version of Code-First, neither will we have the ability to automatically create stored procedures for CRUD operations from your types, nor will we have support for mapping stored procedures in the model. In the future, we want to include these functionalities.

It is feasible to fall back to ObjectContext, as was noted in this thread, however DbContext also offers great APIs to carry out native SQL commands and queries (e.g. DbSet.SqlQuery, DbContext.Database.SqlQuery and DbContext.Database.ExecuteSqlCommand). The fundamental materialization feature included in EF4 is shared by the various SqlQuery versions (like ExecuteStoreQuery: http://msdn.microsoft.com/en-us/library/dd487208.aspx).

Hope this was useful.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow