2

My company's polices forces to use only stored procedures (SP) to talk with DB (no dynamic execution of SELECT, VIEWS on app side available)
Business objects (BO) are fetched from DB.
There is implemented simple BO-DB mapper using SQL Reader and this seems working well.

Form DB side we have one parametrized SPs for each Business Object one SP for all CRUD operations, switched by @MODE parameter) So we don't have separate SP like SP_INSERT, SP_UPDATE, SP_SELECT etc ...

I have read recently lot about linq2SQL, nHibernate, Subsonic etc and those look very interesting.
I noticed main ORM's benefit is flexible queries execution / filtering directly from c# code - in my word I cannot execute such (only SP allowed...)

SO, I'm wondering
- if it is worth to use ORM in my environment?
- can you mention any benefits?
- if so - what ORM you can recommend

What's your view?

Maciej
  • 10,423
  • 17
  • 64
  • 97
  • 1
    my answer here pretty much answer this question as well. http://stackoverflow.com/questions/687762/which-orm-is-the-best-when-using-stored-procedures/6645870#6645870 – Sam Saffron Jul 11 '11 at 06:54

8 Answers8

6

f it is worth to use ORM in my environment?

IMHO, probably not. ORMs focus on the object model and essentially try and treat the database as a dumb store or data. You probably have business logic contained in your stored procedures, which is somewhat counter to the general principles (or at least conventions).

In the very least you'll probably have manual mapping of your objects to and from the stored procedures.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 1
    not necessarily business logic, but data integrity constraints or triggers. That's as valid as putting data validation in a GUI. – gbjbaanb May 12 '10 at 22:44
3

Someone asked a similar question some time ago - about using an ORM to wrap a body of legacy stored procedures. If you have this type of incumbent code base or political constraints on the architecture you might want to look at alternative data access mechanisms and see if they will work better. Fowler's Patterns of Enterprise Application Architecture does a good job of cataloguing various options for this.

The alternative is to go through the political channels and see if you can get the constraint relaxed to 'Use stored procedures in the corner cases where an ORM will not work well, otherwise use the ORM'.

Community
  • 1
  • 1
ConcernedOfTunbridgeWells
  • 64,444
  • 15
  • 143
  • 197
  • 1
    +1 just for PoEAA. It's really a good book, and useful for all kinds of applications, not just "enterprise" applications. – Thomas Owens Jul 06 '09 at 14:34
2

I wonder what was the rationale behind this "architectural" decision.

Manually dealing with low-level ADO.NET stuff (yes, IDataReader is low-level) is almost never a good idea.

NHibernate allows you to specity custom SQL for querying and modifying data, but you lose a great deal of power NHibernate offers by doing so.

Rather, consider using a simple Result-Set Mapper, such as BLToolkit, which will free you from most of grunt work while dealing with sprocs.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • Unfortunately it wasn't my decision. Also I can not change much this approach. Official reason of such design is security (AD/DB roles are used for limit access for particular group of users) +1 for BLToolkit – Maciej Jul 06 '09 at 15:08
2

I'm glad I don't work where you do. I got a VERY painful education in why stored procedures should be avoided unless they're essential for performance or data integrity reasons not long ago. I took on a legacy project. Half the program source was in Java under version control. Half of it was embedded as stored procedures in the database. You pretty much had to have DBA rights to even see it, and working on it remotely was out of the question. It also got into fights with the Microsoft SQL Server driver's transaction manager.

But having said that, the ORM managers I've worked with had no issues with stored procedures, only me.

The main thing was that much of the reason for using an ORM is to make it easier to do "stored procedures" in the application on satellite servers instead of dumping all the work on the database server. And, of course, it's also helpful when all the source code is in one place and in one language.

Tim H
  • 685
  • 3
  • 3
  • I'm also not very happy playing with SPs. But world so designed sometime you have to work with what you get. Only I can do is try to find best approach in that scenario... – Maciej Jul 06 '09 at 15:38
  • 3
    There's nothing wrong with SPs. Why would a programmer not like them, except that they don't fit in the 'point and click and make me a DB object layer' for lazy devs. There are good reasons for using them, an ORM is not a replacement for a SP and a decoupled data layer is as good an architecture as a decoupled GUI. – gbjbaanb May 12 '10 at 22:42
  • 2
    Well SPs are actually better than what ORMs usually provides. Why? Because in everyday apps, you will have to do more DB calls to accomplish the same task that can be done with a single SP call. Not to mention network traffic. Not to mention DB statistics. Not to mention DB precompilation etc. One of the great benefits of ORMs is **transparency**. Database transparency. It queries database for you (to its best abilities that are still worse than manual DB code) and **most importantly** materializes results to strong type objects. You feed it objects and get objects back.Rest is just overhead. – Robert Koritnik Nov 16 '10 at 11:14
1

Some (maybe all, I'm not fully familiar with all of them) ORM tools provide you a class to call you stored procedure. This helps with intellisense, types, names, etc..

SubSonic has this and I find it very helpful to be able to call Project.DAL.SPs.InsertEmployee('John', 'Doe') rather than build the parameter list.

Cody C
  • 4,757
  • 3
  • 29
  • 36
1

Using tools is worth it (even with SPs)

Not exactly ORM tool, but you can use some other data access tool that will make it really easy for you to call those stored procedures and especially materializing their results. This is where these tools will help you greatly. Think of all the things you have to do to use SPs:

  • creating connections and commands
  • handling connection state
  • manage strings related to stored procedure names and their parameters (especially when someone goes and changes something)
  • execute calls and probably convert them to some object instances
  • etc.

And all of this is very repetitive work, you can quite easily avoid.

I favour stored procedures over ORMs, because as soon as you start writing a bit more complex queries that access several tables and join them in any sort of ways, you're into a big pile of trouble and headache. Complex stored procedures usually take much less time to write compared to optimisations and workarounds that you have to do in an ORM to make it snappy (or at least comparable to some degree to an actual stored procedure call). To really optimise some call you have to know ORM tool through and through. Believe me I've been using Entity Framework quite a bit (including the great EF Extensions library that simplifies things enormously).

Anyway. I suggest you take a look at BLToolkit, that is more a DAL tool than an actual ORM tool. I'm using it to call my stored procedures and easily materialize their results.

This tool will actually make it really simple for you to use stored procedures transparently. And if you use T4 template I've also written, you can easily avoid magic strings in your code (stored procedures' names and parameter names). Template automatically imports stored procedures and creates classes with methods that take strong type parameters (C# equivalents to those of your SP parameters).

Your SPs are a bit strange since you have all CRUD operations in a single SP. You could change my T4 template to create all four methods for each SP @Mode call if you wanted to. This would get you the nice:

User newUser = db.User.Create(...);
User existingUser = db.User.Get(...);
db.User.Delete(...);
User updatedUser = db.User.Change(...);

If you don't know what I'm talking about, you can check out my linked blog post where I explain the problem and also solve it with this T4.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
0

The correct answer in all subjects of this nature, is, "it depends". Some things to consider:

  • Will you have business logic in the sprocs?
    • If Yes then some considerations are:
      1. IOC becomes a pain unless you write the sprocs / UDFs in a language that supports easy development of IOC patterns. Some databases allow you to write sprocs/functions in languages such as Java/Perl/Python/C#/PHP. Otherwise if you're using straight up SQL, this may be an issue.
      2. Make sure you know how to develop unit tests against the sprocs. It's really not hard at all but for some reason, there are developers out there that seem to treat this as a problem.
      3. Are the sprocs returning error conditions for BR violations as return data to express error codes or exceptions? If your policy is to bubble exceptions for all business rule violations, you've already made an expensive choice. Bubbling exceptions through another layer, the ORM, is an added performance cost - can you afford it?. (see http://www.linkedin.com/groups/Throw-Exceptions-vs-Return-Error-4318399.S.132967016 and, perhaps-but-not-so-much: http://sylnsr.blogspot.com/search?q=validation)
      4. Do the errors/exceptions from the sprocs need to be translated from internal-type error messages/codes to something more user friendly and possibly a different language? The ORM may be the perfect place to do this since you are adding to the usefulness of the ORM by "mapping" internal-type errors/exceptions generated by the sprocs to something more end user friendly
    • If No then some remaining considerations are:
      1. How much work is it gonna take? Are there ORM frameworks that make this process painless/automated. Entity Framework for example, makes it a breeze to work with sprocs. No hand coding of anything is required. Just use the wizard to map the sprocs and you're done. If the work of setting up the ORM is >= the work of just making a native SQL call then don't bother with an ORM tool (or write your own, especially if you are using an ORDBMS which makes this simpler)
      2. What is your data validation policy? If each layer is responsible for data validation and ORM provides that in an automated manner then it makes it worth it. Waiting for process execution to get all the way to the sprocs to validate the data would be worse the more tiers your application has.
      3. Similar to #2, what is your error/exception handling policy? If your application stack bubbles exceptions through all tiers then things will also get exponentially more expensive the more tiers/frameworks your app stack has. Adding an ORM into the deck would just add another traversal layer.
      4. How bloated is your ORM framework? (do you care?) Some ORM tools add hundreds of lines of code for what you can accomplish in about 4 lines of code by just calling a sproc from your app code.
      5. Do you actually know how your ORM works in the background? Will it impact performance (do you care?) I have worked with an ORM tool that inspected named DB objects (tables, sprocs etc) each time the ORM instantiated a model. This means that it was querying the database twice each time I needed to do something. Once to get a description of the object to map it since it never cached the map and once more to query/execute the object.
      6. How does your team manage ORM generation/maintenance? If you're lucky enough to have bright DBAs that will keep the ORM up-to-date --OR-- have an automated process to keep the ORM up to date (thats how I roll) then yes, ORM is great because you'll know that reliable models will be the only thing you need to concern yourself with and everyone will be happy.
      7. Are you using MVC? Who isn't using MVC? Since you are probably are (should be) using MVC, naturally you would benefit greatly by having an automated way for expressing sprocs and their results and models in your native language. If MVC is over-kill for your particular purposes then ORM is probably a waste of time also.
Michael M
  • 8,185
  • 2
  • 35
  • 51
0

Tooooo late to add an answer but here are my 2 cents:

We prefer tired structured because every layer has its duty (and expertise) and hence let every one do the job what they are best at. The same applies to DB and App as well. DB is meant to store/fetch/update DATA so I would suggest use SPs for all data requests.

Why should my App spend any time combining SQL statement that will eventually go to DB and run.

  • DB should fetch and return the Data
  • App should format it and use it however per requirement

I understand the Dev time will be reduced but for any sizable project, the Performance takes over than Dev time so I am all for SPs than ORM.

psuhas
  • 608
  • 7
  • 13