Why I prefer entity framework to stored procedures



Why Entity Framework (and ORM in general) instead of stored procedures? Below is a an article that pretty well sums up my thoughts on this matter as well.  Believe it or not, the debate over the use of an ORM with respect to data access for an application still comes up.


https://kevinlawry.wordpress.com/2012/08/07/why-i-avoid-stored-procedures-and-you-should-too/

 To summarize my points:
(1) This is the big one - compile time checking.  If your underlying schema changes (e.g. rename a column), and you missed one of the stored procedures that use it, the error will be evident only when hitting that code at run-time.  If instead, you used an ORM like Entity Framework, this will be caught at compile-time.
(2) There is still a place for stored procedures, but the vast majority of your data access code will likely be get-something(s) and sort it.  Its frustrating to maintain dozens of stored procedures that do little other than fetch a list of customers.
(3) Looping.  TSQL is optimized to operate on sets of data.  Yes, you can write a while loop in TSQL, but wouldn't you rather do this with C#?  It's more often the case, that something done in TSQL can just as easily be done with LINQ and EF, and usually cleaner.

There are more, those are probably the big three.

With regards to Entity Framework, there are generally 2 approaches - code first and database first.  Each has its merit, but if you use any kind of source control (and if you're not shame on you), then the database first approach presents a problem with what's known as concurrent development. What this means is that you branch your code and start making changes, and something requires a change in the main branch, merging the EDMX file will often result in conflicts.  These days, I prefer the code first approach, but with an existing database, preferring to design the schema myself so as to control the data types and FK relations myself.  To do this, I now use extensions such as the Reverse POCO generator.  This lets me do concurrent development, while letting me build my own schema. The flow mor eor less goes like this:
- Make SQL changes
- Reverse the EF model changes via the POCO tool
- Code against the updated EF model




No comments:

Post a Comment

Add appsettings.json to .NET 6 Console App

  When you start a new .NET 6 Console app, you will have little more than what you see here.   If one wants to use the json configuration fi...