0

I have searched but couldnt find any useful thing about generating automatically basic CRUD stored procedures when creating the database in code first approach. I am wondering is there a way to do this simply or i should create all the CRUD stored procedure by old fashion?

camadan
  • 103
  • 8
  • 2
    That would slightly defeat the purpose of the ORM. Also, what would be the advantage of using SPs for CRUD operations? – Pablo Romeo May 07 '15 at 19:32
  • Why would it defeat it? I think SPs are always beyond better than classic query execution because of no compilation needed and the results of executions with same parameters are cached. And also i dont want to write every crud operation with my hand. – camadan May 07 '15 at 20:13
  • Adhoc queries are only compiled once and The plan is reused just as with SPs. The same goes for parameters, so performance is hardly a motivation for CRUDs. Except for mass data processing or extremely long queries where the plan could take time to compile. More info here: http://stackoverflow.com/a/2734158/1373170 – Pablo Romeo May 07 '15 at 20:30

1 Answers1

3

It is indeed possible to use Migrations with a Code First Database to generate stored procedures for CRUD operations in Entity Framework 6 and beyond. Note that this is not possible in this manner with Entity Framework 5 and earlier, though you could still use raw SQL calls.

  1. Define your entity in the normal manner, and add a DbSet for the entity to your DbContext class.
  2. Modify the OnModelCreating method of the DbContext to add the following entry: modelBuilder.Entity<SomeEntity>().MapToStoredProcedures();.
  3. Using the Package Manager Console, generate a new migration with add-migration, i.e. add-migration SPGenerate.
  4. Inspect the Up method of your migration to tweak the Stored Procedures to your liking.
  5. Commit the migration to the database by issuing update-database in the Package Manager Console.
Claies
  • 22,124
  • 4
  • 53
  • 77
  • So you could use Sprocs, and EF can be a handy even @ those places as well, good to know. Thnx – Irf Jun 28 '17 at 06:43