Why use Dapper if I don't want to write my query on sql - orm

The project I am working on has 90% of the business logic in stored procedure. I looked at Dapper as a possible path to move some of these business rules to the Application layer. The benefits to me are evident, in that I can do unit testing etc etc.
Dapper seems to help with mapping objects, to classes through sql queries. This is not enough for me, because I'd like to build my queries into an application class like service, and then unit test them before I go to my Repository( aka Dapper).
I'd expect the ORM to translate my query into sql. Dapper seams not to be meant to be used this way. So I wonder what is the point if I still have to build all my business logic in sql.
My question, is do I need a different ORM like hibernate? I guess I am looking for some guidance on how to evaluate this tool.

My experience is that ORM frameworks exist on a spectrum of features and sophistication, often with inversely related compromises in speed and ease of use.
For me, Dapper is right at the end of the spectrum in terms of features and sophistication but with the trade-off that it's speed is exceptional. That's not to say that Dapper is unsophisticated and feature-less, just that it doesn't have features like sessions, query building, etc. that you will find in ORMs at the other end of that spectrum, e.g. NHibernate.
If you want an ORM that will build SQL queries based on an object-oriented domain model, then Dapper is not for you. NHibernate, Entity Framework, LLBLGen and ORMLite(?) are options you can look into. N.b. I expect there are others I've missed.

You have to have a look at SQL Plus Dot Net. It is entity framework in reverse, that is, where entity framework build SQL statements from your C# code, SQL+ .net builds C# code from your SQL.
It truly is the first real innovation in data access in quite a while.

Related

Can ORMs represent every possible SQL query?

I'm currently trying to figure out how powerful ORMs are. I've written pretty simple web applications where you just needed simple CRUD queries and was super happy with the ORM I was using. But for complex analytical queries I didn't even attempt to use the ORM. It might very well be that in the specific cases it was just my limited knowledge. But on a more general note, are there any statements about any ORM that they can / cannot represent any possible SQL query? How powerful are ORMs?
(I'm most familiar with SQLAlchemy of Python)
Please note:
Yes, many ORMs support sending raw SQL. I don't consider that part of the ORM, though. My question is specifically about the ORM part only.
It's subtle. The point of an ORM is to map object to relational constructs. The ORMs I've used (mostly based on the ActiveRecord pattern) do a really good job of mapping basic SQL constructs into the object-oriented development language, and allowing you to reason at the level of an object instance in your app, rather than rows, columns and joins. As you note, this really accelerates CRUD development tasks.
In theory, I think it is possible to represent every SQL Query to an ORM construct (assuming the ORM supports all the SQL constructs in the underlying database engine).
But you probably don't want to. If your application manages orders, having CRUD functionality from the ORM is really useful. But to write the report showing order values by sales person by month in a tabular layout would involve lots of ORM complexity, but could be represented in a fairly simple SQL Query. While the ORM may support every language construct from the underlying database engine, it probably doesn't make any promises about performance.

How does Dapper compare to ADO.NET?

When should Dapper be used instead of ADO.NET?
I would like to understand the pros and cons of Dapper over ADO.NET. What are the advantages of Dapper that would motivate its use?
Dapper is just a tool. What it does is:
make it trivially easy to correctly parameterize queries
make it trivially easy to execute queries (scalar, multi-rows, multi-grids, and no-results)
make it trivially easy to turn results into objects
very efficiently and quickly
What it doesn't do is:
generate a class model for you
generate queries for you
track objects and their changes so you can just call SubmitChanges() (or whatever)
The raw dapper library doesn't provide CRUD features, but the "contrib" additional package does provide basic CRUD.
Basically, it isn't a full-weight ORM, but if you just want to run queries without having to fight an ORM, or pay the overheads associated with an ORM, it is pretty great. If you don't know SQL, the raw library probably isn't for you ("contrib" should be fine, though), but lots of people not only know SQL, but they want to be in control of the SQL (rather than letting the ORM come up with some interpretation of your intent that has not been optimized, etc).
To summarize, reasons might be:
you want excellent raw execution performance with minimal overheads
you want to retain control over your SQL
you don't need or want the object-tracking features of a full-fat ORM
As for "vs ADO.NET":
raw ADO.NET involves a lot more code to write and a lot of edge-cases to remember about (that dapper deals with internally without you needing to worry about them)
but it isn't actually faster - dapper does a lot of meta-programming to store and re-use strategies once it has done what it needs for your query
if you are using provider-specific features that aren't available in raw ADO.NET (for example, passing/fetching SqlGeometry data), those are not directly availalbe in dapper - you'd need to implement an interface to tell it how to handle your scenario, but that isn't hard (note that the specific SqlGeometry example is handled by an additional dapper library)

What is the difference between using a DataContext class and SqlConnection?

This might be a very vague question but I guess I don't really understand what is going on. I asked a question earlier where I was told a simple way to "bind data to objects" is to just run a SqlConnection(connectionString). The response also included a comment saying I could get fancy with L2S and Entity Frameworks, so I looked deeper into those. It seems all you have to do with the DataContext object is point to the database. Why would SqlConnection be a benefit?
What is the difference (or pros/cons) of using either one of these? Is one more "standard"? Is one more modern?
P.S. I asked a lot of questions that don't all need to be answered. I just wanted to add some clarity to my question and how much I don't really understand this topic.
SqlConnection is part of the base, raw ADO.NET class library - the SQL Server part of that library, really. This is the foundation of all data access in .NET.
With raw ADO.NET, you're pretty "bare-bones" and close to the metal - you have to create your SQL queries and execute them, you get back rows and columns, very much like a relational database will give you.
Pros: really close to the SQL, really powerful, best performance
Cons: harder to write, more "glue" code, less type safety, tighter coupling to the underlying database structure
DataContext (Linq-to-SQL) or ObjectContext (Entity Framework) are higher level abstractions - they sit on top of ADO.NET, but they (Linq-to-SQL or Entity Framework) offer so called ORM capabilities - here, you're not really dealing with raw SQL statements and rows/columns, instead, those code generators will create an abstraction layer for you - which is built up from .NET objects. Each table in the database will be turned into a corresponding .NET class, with properties for all the columns in that table.
Also, with L2S and EF, you're typically using LINQ to query - your queries are much more C# like code, and L2s / EF will handle translating those queries you express in C# into actual SQL statements that SQL Server will execute.
Pros: much easier to work with, much nicer to handle (objects with properties vs. raw rows/columns), type safety, ability to query with LINQ, higher dev productivity
Cons: another layer means more translations, a hit on performance, not well suited for certain things (like bulk operations)

What is so great about ORM?

So I'm having a head against the wall moment and hoping somebody can come help either remove the wall or stop my head from moving!!
Over the last 3/4 weeks I've been investigating ORM's in readyness for a new project. The ORM must map to an existing, large and ageing SQL database.
So I tried Subsonic. I really liked v2 and v3 after modding to work nicely with VB and named schemas in SQL was running OK. However, its lack of flexibility of having separate entity properties names vs column names had me pulling my hair out (sorry Rob).
I tried Entity Framework but I found like others it lacking in certain areas.
So I bit the bullet and tried nHibernate but after a week or so getting it working how I liked (with help from Codesmith to generate classes/hbms for me) I'm frustrated with the time it takes to startup (build a config object), despite trying a number of tricks to reduce this time.
I'm essentially after building a DAL class that I can share between apps and websites. Am I barking up the wrong tree? For a legacy project with 100s of tables should I go back to ado.net and use DTOs? Aarrgh!
Sorry for the ranty style of question. I don't have much hair left and I'd like to keep what I have!!
Thanks in advance, Ed
PS. I should add that I know SQL very well and not scared of getting my hands dirty to write fast queries. If anything I don't need to be hid from SQL
ORM let's you:
To map table rows to objects, that are the the workable pieces of object oriented programming.
To automatically navigate through object relationships
To easily add, edit and remove table rows
To query the database in a more intuitive way as you don't have to think of joins (this one will depend on the ORM and the query method)
To transparently handle L1 and L2 cache.
All of the above would have to be handled by hand if you werent using ORM.
PS: I agree to Dmitry as to the startup time of NHibernate (see question comments). Besides, did you try Fluent NHibernate? Fluent NHibernate is impressively easy. I couldn't believe my eyes when I first mapped a database. It's even easier than proprietary ORMs like DevExpress XPO.
The biggest benefit of an ORM tool is that it will help you layer your application correctly. Most project nowadays use a Data Layer to connect to the database. You start from the ORM tool to produce classes that correspond to your database objects. Then you define an interface using these methods. All persistence code uses the methods of this interface. This way the business logic layer is only coupled to this higher-layer interface and needs to know nothing about the database. In fact there should be no dependency on ADO.NET or even NHibernate.
Another advantage of ORM tools is that you de-couple your application from the database server. You could change the db engine and still use the same code. Also there isn't only the complexity of the SQL that the ORM hides from you. It can also help you with transactions logic and connection pooling.
I'd say that for new projects an ORM tool is a necessity. For legacy projects it isn't so much beneficial, unless of course you have the time/money to start from scratch.
In my experience, most ORMs end up being way more complex than SQL. Which defeats the entire purpose of using them.
One solution I'm enthusiastic about is LINQ2SQL. It excels as a thin layer about stored procedures or views. It's really easy to use and doesn't try to hide SQL.
There are basically two questions here:
What's great about ORMs? There are similar questions on Stackoverflow. See:
What are the advantages of using an ORM?
Is everyone here jumping on the ORM band wagon?
How can I improve NHibernate startup time? See:
http://ayende.com/Blog/archive/2007/10/26/Real-World-NHibernate-Reducing-startup-times-for-large-amount-of.aspx
http://nhforge.org/blogs/nhibernate/archive/2009/03/13/an-improvement-on-sessionfactory-initialization.aspx

When choosing an ORM, is LINQ to SQL or LINQ to Entities better than NHibernate?

I find I can do more with NHibernate, and even Castle than with the Linq to Entities, or linq to SQL.
Am I crazy?
No you're not crazy. nHibernate is a full OR Mapper, Linq to SQL and Linq to Entities don't implement everything you'd expect from an OR mapper and targeted at a slightly different group of developers.
But don't let that put you off linq though. Linq is still a pretty good idea.. Try Linq to nHibernate :-)
The big drawbacks to NHibernate, Castle, etc., is that they're not exactly light-weight (especially NHibernate.)
Linq to SQL is good for a light-weight, limited use ORM.
I've used both NHibernate and LINQ to SQL. From my point of view it depends on the project, if I need something quick, I would choose L2S, it's so simple to create the dbml mapping and start using it. If I'm developing a more highlevel enterprise solution I would go for the tried and trusted ORM - NHibernate, I find the logging & transaction features simple to use.
LINQ to SQL has a relatively short learning curve, NHibernate has a much steeper learning curve.
LINQ to SQL only supports SQL Server, so if you've an Oracle database then the decision is already made - NHibernate.
I'd recommend checking out http://www.summerofnhibernate.com/ for excellent screencasts on learning NHibernate.
One thing to bear in mind is that NHibernate can be an absolute pig to configure - especially since its based mainly on XML config files because of its roots as the original Hibernate.
Fluent NHibernate goes some way to making this less painful.
Linq certainly though fits in with the general 'way' in which .NET works.
Blockquote Linq certainly though fits in with the general 'way' in which .NET works
Yikes, this kind of sentiment scares me. The RAD stuff built into .net is NOT how dot net works, it's just a tool set for getting prototypes up. .NET allows us to do full DDD applications, w/ high levels of cohesion, seperations of concerns, and allows us to write decoupled code, despite all the attemps ms makes to couple things. I would strongly disagree that .net likes to be coupled, certian tools like to be coupled, i'll include linq to sql in this fray. linq to sql destroys the idea of having a seperate domain model. I cringe at the thought of using my database schema as the underlying model objects. Proper ORM tools should allow us to model our domain first, then link our relational database to these models. NOT the other way around.
I have not tried the Entity Framework, but I definitely would recommend NHibernate over Linq to SQL; The biggest reason I can give is just the control. Linq to SQL likes to have a lot more control over everything, loading the object and maintaining all kinds of tracking information about the object. If you serialize/deserialize, the tracking information can be lost and strange things can happen when saving it again. NHibernate works more as a repository should - You hand it whatever object you want (that you have configured it to understand, of course), and it puts it away in the database, regardless of what you've done with it.