When choosing an ORM, is LINQ to SQL or LINQ to Entities better than NHibernate? - 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.

Related

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

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.

linq to sql, why to use it in MVC instead of traditional queries?

is it necessary to use LINQ for sql purposes in MVC ? can't we use traditional queries like:
Select name from tbl where id = 2;
instead of LINQ ? and why linq in any case ?
ASP.NET MVC in no way restricts your choice of data access technology. In fact, model binding works with objects, and MVC has no idea whether your objects represent some database or not.
Besides, if you were to use LINQ at all, you would do best to use Entity Framework (a.k.a. LINQ to Entities) and not LINQ to SQL, which is much more limited.
Linq to SQL, EntityFramework, nHibernate - are ORM (Object-relational mapping) tools. ORM represent database objects as standard .NET classes.
Raw SQL can be used, when you are inserting a lot of data, and you need a good performance. In all other cases you should to use ORM.
And if you decide to use ORM, I advise you to use EntityFramework; it's more powerful than LINQ to SQL.
You don't need to use linq at all. I usually use dapper.net for my data layer, mapping SQL queries to objects. It's personal preference.
You are not obliged to use Entities Framework, as you are not obliged to use anything in particular.
Microsoft strongly suggests using the Entities Framework because it is an ORM integrating very easily with the whole Microsoft ecosystem, using the LINQ query language which is integrated in the .NET languages specification. This integration happens through the Linq to Entities query language and the respective tools provided in Visual Studio.
As you will see, Entities Framework (as every other ORM) has the overhead of the learning but in my opinion, it totally pays you back as using an ORM leads to faster development and more maintainable source code. I would strongly suggest using an ORM (it has many advantages) and I suppose since you are already familiar with Microsoft ecosystem, Entities Framework would be the best choice.
Hope I helped!
Well, if you want to use this style of queries you can use stored procedures this is to close to the normal query, just and a Linq-to-SQL file into your project and drag and drop you stored procedures then you can use them like methods and this is a link http://msdn.microsoft.com/en-us/library/bb386946.aspx
Note that Linq-to-SQL is integrated only with SQL Server
No, you do not have to use LINQ at all, or any other ORM frameworks, you an work directly against a database.
In .Net this is typically done using ADO.Net, for example using the System.Data.SQL namespace.
See code examples and official documentation here

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

Would you use NHibernate for a project with a legacy database, which is partly out of your control?

For me the answer is currently: No, I would use iBatis, because NHibernate is a pain, when the database model and the object model are not in synch. If I don't have full control over the database I end up with a lot of work.
Why do I ask?
Well, first of all: I never used NHibernate. I just know it from the surface. I have read about the advantages of iBatis for legacy databases.
Second: Recently I had a discussion with someone who worked with Hibernate (jep, without 'N' before Hibernate). He told me that the ORM frameworks are now pretty advanced and advocated Hibernate. Since I was not interested in NHibernate, I didn't keep track of the recent developments.
Maybe I its time to rethink my answer, or not?
iBatis is certainly easy to map objects to legacy database systems.
More recently NHibernate 1.2 and 2.0 have a feature set that may make you rethink iBatis.
NHibernate works with composite keys, which can occur frequently in older databases, they aren't always pleasant to work with but support is there for this.
NHibernate can utilise Stored Procedures for CRUD operations on entities, also database views.
Collections can be custom stored procedures or SQL queries. Collections can use the property-ref attribute when the Foreign Key relationship doesn't map directly to the Primary Key on the other side.
Some of these features may take away from the performance/power of nhibernate, ie Lazy Loading with property-ref doesn't work (at all?), but is most cases there are reasons for this.
Other points: (which aren't really related to your legacy database but still can help decide on a technology choice)
The Nhibernate community appears much richer than the iBatis. I'm on both lists and the volume of support for NHibernate is quite large compared to the iBatis group. So support should be easier.
Also there is a growing amount of contrib/3rd party tools for NHibernate. Things like The NHibernate Profiler, the Nhibernate Query Analyzer, NHibernate Contrib, Fluent NHibernate to name a few.
Perhaps you can expand on what advantages you believe iBatis currently has. NHibernate has certainly been quite active recently and has gained many new features, a lot of which do assist in legacy/hard to modify schemas.
And to answer the question, yes we do use NHibernate with legacy databases that have awful relationships, composite keys, broken relationships. We still also have a small amount of code based on iBatis. We no longer write any more iBatis code though.
Yes, consider NHibernate. It's the gold standard for a reason. I have heard that iBATIS supports crazy mapping possibilities, but with NHibernate's IUserType you can map anything, even really strange columns.
#Ahmad, the entire point of ORM is to prevent a tight coupling between your objects and your schema. If you have this problem you're doing it wrong.
Also, with NHibernate there are plenty of options for custom queries, formula properties and stored procedures. HQL is extremely powerful and Criteria is flexible.
I think you'll be doing your clients a disservice if you don't at least spike NHibernate.
I've been using nHibernate in an existing application. I use it for all new development, I have no intention of porting the existing stuff over either there just isn't a compelling reason but for new stuff on the project it works great.
If you are going to port the code over then you should be able to change the database to match better with your domain model, without much impact (depending on how leaky your database is ie who access it). Changing the domain model would impact the application however.

Best practices for querying with NHibernate

I've come back to using NHibernate after using other technologies (CSLA and Subsonic) for a couple of years, and I'm finding the querying a bit frustrating, especially when compared to Subsonic. I was wondering what other approaches people are using?
The Hibernate Query Language doesn't feel right to me, seems too much like writing SQL, which to my mind is one of the reason to use an ORM tools so I don't have to, furthermore it's all in XML, which means it's poor for refactoring, and errors will only be discovered at runtime?
Criteria Queries, don't seem fluid enough.
I've read that Ayende's NHibernate Query Generator, is a useful tool, is this what people are using? What else is out there?
EDIT: Worth a read
http://www.ayende.com/Blog/archive/2007/03/17/Implementing-Linq-for-NHibernate-A-How-To-Guide--Part.aspx
The thing with LINQ for NHibernate is still in beta; I'm looking forward to NHibernate 2.1, where they say it will finally make the cut.
I made a presentation on LINQ for NHibernate around a month ago, you might find it useful. I blogged about it here, including slides and code:
LINQ for NHibernate: O/R Mapping in Visual Studio 2008 Slides and Code
To rid yourself of the XML, try Fluent NHibernate
Linq2NH isn't fully baked yet. The core team is working on a different implementation than the one in NH Contrib. It works fine for simple queries though. Use sparingly if at all for best results.
As for how to query (hql vs. Criteria vs. Linq2NH), expose intention-revealing methods (GetProductsForOrder(Order order), GetCustomersThatPurchasedProduct(Product product), etc) on your repository interface and implement them in the best way. Simple queries may be easier with hql, while using the specification pattern you may find the Criteria API to be a better fit. That stuff just stays encapsulated in your repository, and if your tests pass it doesn't much matter how you implement.
I've found that the Criteria API is cumbersome and limiting but flexible. HQL is more my style (and it's better than SQL - it's object based, not schema based) and seems to work better for me for simple GetX methods..
I use Linq for NHibernate by default. When I hit bugs or limitations, I switch to HQL.
It's a clean approach if you keep all your queries together in a data access class, such as a Repository.
public class CustomerRepostitory()
{
//LINQ for NHibernate
public Customer[] FindCustomerByEmail(string email)
{
return (from c in _session.Linq<Customer>() where c.Email == email).FirstOrDefault();
}
//HQL
public Customer[] FindBestBuyers()
{
var q = _session.CreateQuery("...insert complex HQL here...");
return q.List<Customer>();
}
}
You asked about refactoring. LINQ is obviously taken care of by the IDE, so for any remaining HQL, it's fairly easy to scan these repository classes and change HQL by hand.
Putting HQL in XML files is a good practice, maybe see if the ReSharper NHIbernate plugin can handle the query refactoring by now?
A big improvement when writing or refactoring queries (HQL or LINQ) is to put finder methods under unit test. This way you can quickly tweak the HQL/LINQ until you get a green bar. The compile/test/feedback loop is very fast, especially if you use an in-memory database for testing.
Also, if you forget to edit the HQL after refactoring, the unit tests should let you know about your broken HQL very quickly.
An alternative to LINQ-to-NHibernate and Ayende's NHQG is to generate NHibernate Expressions/Restrictions from C#3 Expressions. This way you get a more strongly-typed Criteria API.
See:
http://bugsquash.blogspot.com/2008/03/strongly-typed-nhibernate-criteria-with.html
http://www.kowitz.net/archive/2008/08/17/what-would-nhibernate-icriteria-look-like-in-.net-3.5.aspx
http://nhibernate.info/blog/2009/01/07/typesafe-icriteria-using-lambda-expressions.html
scrap nHibernate and go back to Subsonic if you can. In my opinion, Subsonic is a far more fluent and testable ORM/DAL. I absolutely hate HQL what's the point of a weakly typed query in an ORM? And why would I use Linq/nH/SQL when I can just use Linq to SQL and cut out a layer?
nHibernate was a good ORM when Subsonic wasn't around, but now, it's just plain awful to work with in comparison. It easily takes me 2 times longer to do stuff with nHibernate vs Subsonic. Testing is a pain since nHibernate is runtime, so now I need to employ a few QA engineers to "click" around the site instead of getting a compile time error.