Please recommend .NET ORM for N-tier development [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I need to choose carefully .NET ORM for N-tier application.
That means, the I will have the server (WCF service), which exposes the data, and client, which displays it.
The ORM should support all the related serialization issues smoothly - the objects or collections of objects, or whatever must travel across process boundaries. Ideally, the usage in multiprocess environment should be the same as in single process.
The criteria are:
Flexibility of db schema mapping to objects (preferred)
Ease of use
Free, open source (preferred)
Must be suitable for N-tier (multi-process multi-domain applications)
Performance
Tools to integrate with Visual Studio (preferred)
Testability
Adoption, availability of documentation
Wide range of RDBMS supported (preferred; we are using MSSQL, but I wouldn't like to be tied to it)
DB agnostic - different DBs, same API

Having worked with the following:
NHibernate
LLBLGen
Entity Framework
LINQ to SQL
DataObjects.Net
OpenAccess
DataTables
I can most certainly say that DataTables are superior...no just kidding. All of them do have their strengths and weaknesses.
Mainly, I have found that these strengths and wekanesses are associated with the general type of ORM, which falls into the following two categories
Heavy-weight
LLBLGen, OpenAccess, Entity Framework (pre 4.0), DataObjects all fall into this category. Heavy weight ORMs typically have entities and collections that inherit from a base class specific to the ORM (ie. EntityBase). These ORMs often offer rich design time support, code generation and in depth runtime features (such as state tracking, transaction tracking, association maintanance, etc.).
The Pro: Easier, faster development upfront leveraging the built in API for interacting with entities themselves at runtime (ie. from LLBLGen entity.Fields["MyField"].IsChanged or entity.IsNew or entity.Fields["MyField"].DbValue
The Con: Heaviness and dependencies. With these ORMs, your business objects are now tied directly into the ORM API. What if you want to change to another ORM? And what's to prevent junior developers from abusing advanced features of the ORM API to fix a simple problem with a complex solution (I've seen this a ton)? Memory usage is also a big problem with these ORMs. A collection of 5,000+ entities can easily take up 100MB of RAM with some of the above ORMs. Serialization is another problem. With the heaviness of the objects, serialization can be very slow...and it probably won't work correctly deserializing on the other side of the wire (WCF or .NET remoting, etc.). Associations may end up not re-associated correctly or certain fields may not be preserved. Several of the ORMs above have built in serialization mechanisms to improve support and speed...but none that I've seen offer full support for different formats (ie. you get binary, but not json or xml serialization support).
Light-weight
LINQ to SQL, Entity Framework POCO, NHibernate (sort of) fall into this cateogry. Light-weight ORMs typically use POCOs that you can design yourself in a file in VS (of course you can use a T4 template or a code generator too).
The Pro: Lightweight. Keeps it simple. ORM agnostic business objects.
The Con: Less features, such as entity graph maintance, state tracking, etc.
Regardless of what ORM you choose, my personal preference is to stick to LINQ, and ORM independent retrieval syntax (not the ORM's own API for fetching, if it has one).
With regard to the specific ones mentioned, here are my brief thoughts:
- NHibernate: Behind the times tech wise. Lots of maintainence of xml mapping files (though Fluent NHibernate does alleviate this).
LLBLGen: Most mature ORM I've worked with. Easy to start up a new project and get going. Best designer. VERY heavy weight. Rich VERY powerful API. Best speed I've encountered. Because it's not the new kid on the block, some of the newer features leveraging newer technology aren't implemented as well as they should be (LINQ specifically).
Entity Framework: POCO class in 4.0 looks promising. 3.5 doesn't have this and I wouldn't even consider it. Even in 4.0, doesn't have great LINQ support and generates poor SQL (can makes hundreds of DB queries for a single LINQ query). Designer support is poor when it comes to larger projects.
LINQ to SQL: Great LINQ support (better than any other except DataObjects.Net). Mediocre persistence (save/update) support. Very lightweight (POCO). Designer support is poor all around (no refresh from DB). Poor performance on advanced LINQ queries (can make hundreds of DB queries)
DataObjects.Net: Really great LINQ support and performance. Offers the closest thing I've seen to POCO in a heavy-weight ORM. Really new, powerful, promising technology. Very flexible.
OpenAccess: Haven't worked with it a ton, but it reminds me somewhat of LLBLGen, but not as feature rich or mature.
DataTables: No comment

Why not try NHibernate?

I would recommend Entity Framework v4. It has improved beyond dramatically since v1, and supports everything you require except being open source:
EF supports a very wide variety of mappings, including TPH, TPT, and TPC. Supports POCO mapping, allowing you to keep your persistence logic separate from your domain.
EF has extensive and excellent support for LINQ, providing easy to use, compile-time checked querying of your model. EF Futures components such as Code-Only simplify working with EF even more, providing a pure code, compile-time checked, fluent API for defining your model. By opting for convention over configuration, Code-Only can radically reduce your model design time, allowing you to get down to business without all the hassle of tinkering with a visual model and multiple XML mapping files.
It is free as part of .NET 4. (Sorry, Open Source preference can't be met here.)
EF provides an excellent N-Tier solution OOB via self-tracking entities
Self-tracking information uses an open xml format to transfer tracking data, so tracking support could be added to non-.NET platforms
Performance of EF v4 is very good, as extensive work was done on the query generator
See the ADO.NET Blog entry on the subject
EF provides extremely rich visual design tools, and allows extensive customization of code generation via custom T4 templates and workflows
EF v4 introduced numerous interfaces, including the IObjectSet<T> and IDbSet<T> interfaces, which greatly improve the unit testability of your custom contexts
EF v4 is an integral part of .NET 4 and a central component of all of Microsofts current and future data initiatives. As a part of .NET, its documentation is quite extensive: MSDN, EFDesign Blog, ADO.NET Blog, dozens of .NET and Programming sites and blogs provide a tremendous amount of documentation and support for the platform.

Another vote for EF here.
Very easily unit testable. You can write your own Domain Entities and have them be reasonably free of persistence awareness using POCO approach. You can then mock the database interface and test the application logic without actual database.
Supports LINQ so that if you write your LINQ properly, it will only translate a single SQL statement being sent to the server.

I've been using a product called LightSpeed, it works very well and seamlessly integrates into Visual Studio 2010 & 2008. I have been using it with Sqlite, however it supports numerous rdbms. It also has a very nice feature that allows you to create POCO objects that can be used with WCF, great time saver! At first I was using the free Express Edition but soon upgraded.
LightSpeed is the best high performance .NET domain modeling and O/R mapping framework available. First class LINQ support, Visual Studio 2008 & 2010 designer integration and our famous high performance core framework means you can create rich domain-driven models more quickly and easily than ever before.

Having used OpenAccess on several projects, I must say that it meets all the above criteria.
One system I worked on was based on WCF services talking to several client types (smart, web, other WCF services, etc.) Through a layered architecture the WCF services used OpenAccess as persistence mechanism.
I am especially fond of the scaling that OpenAccess performs.. The intelligent Level 2 cache (L2 cache) does a perfect job there and it is of cause distributable.
Actually I wouldn't call OA heavy weight... You don't even inherit from a base class. Also it is a big plus that there are tools to perform the day-to-day developer tasks (create a new DB schema, merge schemas and so on) integrated into visual studio.

About EF4...
Please do not use it in a large project, with many tables and lots of data and many users. I've made this mistake and now I'm looking for a replacement.
1-Bad query generation, especially in large TPT hierarchies. Be prepared for a 5000 line query for a hierarchy of 15 tables!
2-Extremely slow designer when the number of tables grows. 45 Seconds just to collapse/expand an entity in a model with 240 entities.
3-Serious problem with x-to-many relationships. Suppose you have Order and Customer entity. Each order has a Customer and each Customer has many Orders. There is a property, named Orders in Customer class that will be populated without you ever actually needing that data. This meant, in our system, that collections up to 1800000 entities be fetched for no actual reason. When this happens inside a transaction with Snapshot isolation level... that brings the whole system to failure. There is no actual solution to this problem, one that has no serious drawbacks. Just read the DataObjects.Net's documentation and see how they've takled this problem. I found that paying 200 or 500 euros is nothing compared to what you get. I may even get the version with source code.
If I'm unable to integrate my system with DO.Net, I'll look for another one, but this EF thing, it has to go!

Related

.netTiers + Codesmith VS Entity Framework .Net C#

I have question about pros and cons what should I mention when I compare netTiers (with codesmith) and Entity Framework
This question was asked many times around netTiers (with codesmith) and all topics that I have found are very old, older then time when Entity Framework got so popular probably.
I am actually very comfortable with Entity framework (not proficient, but I like it and I use it a lot) and am not very close to netTiers (with codesmith), that's why I want to know what to decide when I see netTiers in complex project.
One option is to stay and handle all problems face to face that I assume that it takes enormous amount of time.
Another - to use already managed and pre-designed fancy utilities from Microsoft (that's how beautiful entity framework seems to appear to me, after I spent few days with netTiers).
Comfort level is a big one, if you are the primary developer, and you like Entity Framework then that is a very big reason to stick with it. However, in your case, it sounds like you are coming in to a new environment that is using netTiers, you prefer EF, and you want an excuse to switch to your favorite framework.
I have used both frameworks, and I started using both of them about the same time. In my opinion they both have areas they shine in.
EF is better for small projects, it is primarily used for a code first approach and shines in allowing the application to upgrade the database as new versions of the app are rolled out. However, it also promotes poor sql query generation using linq-to-sql and consequently tends to have a lower overall data throughput then netTiers. If the developer has little direct database experience, or has no direct management access to the database, then EF will likely be a more attractive option for them as it will allow them to take back a little control.
netTiers shines in reducing code writing and maintenance. Unlike EF it only supports a database first approach. netTiers auto generates the entire DAL for you, and keeps it updated at the click of a generation button. It works better for larger projects, particularly web projects where you have full control over the hosted database and can easily push upgrades to it. netTiers Achilles heel is the CodeSmith config used to generate the DAL. This config probably needs to be kept in source control, because if it is ever lost and was highly customized, then it can be very difficult to re-create that so your DAL is generated the same way the next time you push the button (this can be an issue during developer turnover). netTiers also allows you to see all the DAL code, and debug as needed, whereas EF is just a dll you are stuck with.
Historically, netTiers was developed before EF really became a viable framework. It was developed to solve an issue that really had not yet been addressed. Since that time EF has really grown up and in many areas has surpassed netTiers, which has caused netTiers popularity to plummet. EF is far more configurable and flexible than netTiers. However, EF has never been able to touch netTiers in the area of code generation, and takes a lot more work to ensure it stays on par with netTiers in data throughput.
I have seen apps where developers have manually modified DAL code, which breaks the power of netTiers to reduce coding time by auto generating the DAL. As long as you are not stuck in that situation and you already have a solid netTiers setup, then trying to rip it out and convert over to EF would probably be a waste of effort.

Data access : Fluent Nhibernate vs ADO.NET vs Linq to Sql?

Creating My Windows Form Application and using ADO.Net as Data Access layer and
SQL server as my Back End with lots of SP's.
Do i still stick to ADO.NET or go to studying FnH or Linq to SQL? Which shall i choose? Or i still stick in ADO.NET?
Can you give me Recommended WebSites on EF or FluentNhibernate for kick of tutorials..
Thanks in Regards
It's really just up to you to pick one - they're all valid technologies.
If you're already familiar with the low-level ADO.NET constructs, and you don't feel like putting the time into learning a different methodology, you can stick with plain old ADO.NET - this is not going away anytime soon.
If you want to start off with a very simple ORM, I would suggest LINQ to SQL. However, Microsoft has basically left LINQ to SQL in the dust in favor of Entity Framework, so if your project has long-term maintenance concerns, LINQ to SQL may or may not be the best choice. It is a really nice, lightweight, easy-to-use framework though...
If you want to learn the latest MS data access technology, you could try Entity Framework. The initial setup is not too bad, but Entity Framework is a beast, so there might be a bit of a learning curve at some point, if you run into something that works differently than you expect, or you want to learn more. EF is fairly full-featured at this point, but it still lacks some of the functions offered by more mature data access technologies like NHibernate.
Finally, if you want to try something different than the Microsoft offerings, NHibernate is a great framework. You're not going to find the entity designers, property pages, wizards, hand-holding, and stuff like that, but that's almost the point of NHibnerate. In Fluent NHibernate, the primary focus can be on your domain code, and less on the database, which makes it very conducive to unit testing. Entity Framework has gotten better with persistence ignorance, but it still feels a bit heavy-weight compared to NHibernate.
In addition to these, there are several other solid data access technologies that you could look into, but I hope this gives you some info to start with.

DAL "Typed DataSets" or Custom Business Object

I would like your opinions regarding "DataSet Designer" and DAL (Data Access Layer) best practices.
I use Visual Studio 2010 Framework .NEt 4.0.
For my understanding "DataSet Designer" allow me to create automatically strictly Typed-DataSet with DataTable and Adapter, this consist in DAL directly in Visual Studio 2010.
I would like to know:
- If in real scenario "DataSet Designer" is working well, or is better write Custom Business Object.
- If exist other new solution introduced in .net 4.0
Thanks for your support! :-)
I have to work with typed datasets and it is a nightmare. If you have an option never use them. Everything is better.
With the advent of the .Net 4.0 framework and the introduction of LINQ to SQL, I've been adopting a customized DAL of strictly written business objects. We experimented with Entity Framework briefly, but ultimately concluded that it is very similar to DataSets in that the auto-generated code, while handy, is just too bloated with extra junk that we ultimately didn't use.
We've found that writing LINQ into our DAL and extracting data pulls into our custom classes, we are able to streamline our data access and control the usage of the data functionally. It has been a very handy process, but it has taken a little bit for the junior developers to grip onto it.
I would suggest a ORM like Entity Framework or Nhibernate.
Data Sets smells too much to database way of thinking and I personally had a lot of problems working with them. They just get broken quite often and throw weird errors that are hard to troubleshoot.
Some other related questions you may find interesting
What are the advantages of using an ORM?
ASP.NET DataSet vs Business Objects / ORM
Use ADO.NET Entity Framework, which is where the future of Microsoft's ORM is going. Or, consider an open-source one like NHibernate...
HTH.
At my company we've been using Typed DataSets for a little while now, and have had a generally positive experience. I understand that many people don't like DataSets, and there are certainly newer data access tools out there, but since you asked about a real-world scenario, here are some of my requirements and findings:
Need to be able to read SQL Server, MS Access, and FoxPro data sources
SQL Server access is only through SPROC calls (not my choice)
Relatively easy to learn, especially to developers new to ASP.NET
I've personally explored low level ado.net access, typed datasets, linq-to-sql, and simply writing custom data access classes. I have not looked at the Entity Framework yet, as the version included in VS2008 seemed to have some mixed reviews, and I did not have access to VS2010 until just recently(I do plan to review EF sometime this year yet).
We chose to use Typed DataSets because they seemed to offer faster development against SPROCS and we found a very comprehensive tutorial by Scott Mitchell on the asp.net site: http://www.asp.net/data-access/tutorials.
As to our experience thus far, it has mostly been good. The DataSet designer generates a huge amount of code even for small number of Tables (<20). Making changes in the SPROCS has caused a few headaches, but I'd like to be shown a tool that would make this easier.
One thing you might try to make your decision easier: Come up with a small domain problem like a customer edit page or order entry page, and implement it multiple times using a variety of technologies. It takes some time to do this, but it is a good way to learn and you can compare the technologies for yourself. We did this and it seemed to help a lot.
I will personally prefer custom business objects with their flexibility but its more work. Also look at with Entity Framework and Linq To Sql. Entity Fx has got a lot more flexibility in .NET 4.0. This article should get you started on Entity Fx.
If anything I think you should look into Entity Framework. There are lots of great tutorials out there to get you started.
I personally agree with Joel Etherton, conditionally.
If you have a small enough project that even with EF's bloat you're still not looking at too much shenanigan-code, I would say the expediency it offers is worthwhile. However in larger codebases, it can become a lot to get your hands around so much bloat.
The other benefit to EF vs older style business objects which goes unmentioned though, is with EF implementation you will probably get easier upgrades to newer .NET versions taking advantage of benefits in the next .NET without having to rewrite a bunch of code by hand. (This can also be a double-edged sword as upgrading to new .NET with EF may affect the behaviour of your dal as opposed to a hand-written dal is less likely to be so affected.)
That said, I agree with Joel Etherton, write the simplest smallest dal you can implementing LINQ, the dal is always too important to make overly-complex whenever it can be avoided.
If you do not want to waste you time do not learn DataSets. Study general concepts of object-relational mapping, their pros and cons. Look at projects like Hibernate for Java or Doctrine for PHP. Approaches behind DataTables and DataSets which provide just wrapping of database objects is over. Your framework should guide you to design you domain model, not the database schema.
NHibernate. Especially if you are using Oracle.

What is the most used method for accessing database from C# nowadays [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Ok, I am asking this question because I am totally confused. I used to use normal approach to access databases from C#(I mean by using SQLConnection, OracleConnection, SQLCommand, executequery etc.). Then I heard about ADO.NET, ORM and learned NHibernate(not a pro, but I can manage).
Recently I don't see any particular activities regarding NHibernate a lot. People around me who used to use NHibernate(and was a fan) are now moving to other methods.
So what is the most used database access method nowadays? How can I keep track of this changing trend?
The most common methods are probably these:
LINQ to SQL
Entity Framework
ADO.NET directly
NHibernate
Other O/RMs.
All of them are still in use and they have different advantages and disadvantages. I think Microsoft are currently trying to encourage people to use the Entity Framework.
There is only one way - ADO.NET for SQL Server. More particular, the Connection and Reader objects in there. Now, you may say there are things like Entity Framework - but interesting enough they are ABOVE the real access layer, using both access elements named before. Even DataSets are a higher layer (the data is read through a DataReader).
So what is the most used database
access method nowadays?
I bet it STILL is datasets. The amount of uneducated following the drag and drop principle is IMHO still the majority, and this approach in visual studio leads to Datasets.
Professionals use an ORM of sorts. Entity Framework is pretty pushed now by people who mostly do not really know what an ORM can do it programmed properly. Right now my best bet is still NHibernate for a high quality layer.
In my opinion, for rapid application development, using an ORM tool like LLBLGEN is the best solution. You can speed up the development progress dramatically.
So, there are few technologies to access database in .NET.
At first, this is ADO.NET. It is one 'true' access technology, because other (like NHibernate, LINQ2SQL, Entity Framework (they are all ORM)) uses ADO.NET to actually connect to database and execute commands against it. Of course, .NET provides other ways to interact with database, for example, importing some of COM interface, but they are not natural.
Also, tools that helps you communicate with database exists. It is ADO.NET extensions (like Enterprise Library Data access), and tools allows you to work with objects (named entities) which are natural for object-oriented runtime as .NET, but load and save that entities from the database. These tools named ORM (object-relational mapper), and modern tools are easy to use and nice.
I personally love Linq To Sql using CodeSmith to generate the entities, more specifically I think Plinqo has the most ease of extensibility. It allows you to separate all of Entity objects into separate files with an editable version and a generated one. This allows you to extend your DAL with as many helper functions that you need. it has a Visual Studio add-in that lets you regenerate all of your entities with just a click.
I normally to database first design, so I make my changes in the database, go to VS regenerate the entities, and then I can continue coding.
Regardless of what you choose, I think an important factor for an ORM is being able to configure it to meet your needs, there is no one size fits all.
BTW, I don't work for CodeSmith, I just use it :)
NHibernate and Entity Framework are great tools to abstract the database (EF Code First is amazing), but in some cases, this is bad.
I've seen many applications that the poor performance is on database connection, and NH or EF do not allow to control queries or the use of most powerfull features of the database, unless you are an expert in ORMs (unfortunately, are uncommon).
Personally, I prefer to maintain control in my hands.
I created a tool, Thunderstruck, that I use in my projects and recently I put the source on Github.
Well if I have to pick one, I would say Entity Framework that's the most generic way,
LINQ to SLQ is being deprecated in the future, NHibernate will be more and more in the future.
But the best advise is probably try to pick one for the whole team! even if it has downside they all have at some point or an other.

Are there good reasons not to use an ORM? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
During my apprenticeship, I have used NHibernate for some smaller projects which I mostly coded and designed on my own. Now, before starting some bigger project, the discussion arose how to design data access and whether or not to use an ORM layer. As I am still in my apprenticeship and still consider myself a beginner in enterprise programming, I did not really try to push in my opinion, which is that using an object relational mapper to the database can ease development quite a lot. The other coders in the development team are much more experienced than me, so I think I will just do what they say. :-)
However, I do not completely understand two of the main reasons for not using NHibernate or a similar project:
One can just build one’s own data access objects with SQL queries and copy those queries out of Microsoft SQL Server Management Studio.
Debugging an ORM can be hard.
So, of course I could just build my data access layer with a lot of SELECTs etc, but here I miss the advantage of automatic joins, lazy-loading proxy classes and a lower maintenance effort if a table gets a new column or a column gets renamed. (Updating numerous SELECT, INSERT and UPDATE queries vs. updating the mapping config and possibly refactoring the business classes and DTOs.)
Also, using NHibernate you can run into unforeseen problems if you do not know the framework very well. That could be, for example, trusting the Table.hbm.xml where you set a string’s length to be automatically validated. However, I can also imagine similar bugs in a “simple” SqlConnection query based data access layer.
Finally, are those arguments mentioned above really a good reason not to utilise an ORM for a non-trivial database based enterprise application? Are there probably other arguments they/I might have missed?
(I should probably add that I think this is like the first “big” .NET/C# based application which will require teamwork. Good practices, which are seen as pretty normal on Stack Overflow, such as unit testing or continuous integration, are non-existing here up to now.)
The short answer is yes, there are really good reasons. As a matter of fact there are cases where you just cannot use an ORM.
Case in point, I work for a large enterprise financial institution and we have to follow a lot of security guidelines. To meet the rules and regulations that are put upon us, the only way to pass audits is to keep data access within stored procedures. Now some may say that's just plain stupid, but honestly it isn't. Using an ORM tool means the tool/developer can insert, select, update or delete whatever he or she wants. Stored procedures provide a lot more security, especially in environments when dealing with client data. I think this is the biggest reason to consider. Security.
The sweet spot of ORMs
ORMs are useful for automating the 95%+ of queries where they are applicable. Their particular strength is where you have an application with a strong object model architecture and a database that plays nicely with that object model. If you're doing a new build and have strong modelling skills on your team then you will probably get good results with an ORM.
You may well have a handful of queries that are better done by hand. In this case, don't be afraid to write a few stored procedures to handle this. Even if you intend to port your app across multiple DBMS platforms the database dependent code will be in a minority. Bearing in mind that you will need to test your application on any platform on which you intend to support it, a little bit of extra porting effort for some stored procedures isn't going to make a lot of difference to your TCO. For a first approximation, 98% portable is just as good as 100% portable, and far better than convoluted or poorly performing solutions to work around the limits of an ORM.
I have seen the former approach work well on a very large (100's of staff-years) J2EE project.
Where an ORM may not be the best fit
In other cases there may be approaches that suit the application better than an ORM. Fowler's Patterns of Enterprise Application Architecture has a section on data access patterns that does a fairly good job of cataloguing various approaches to this. Some examples I've seen of situations where an ORM may not be applicable are:
On an application with a substantial legacy code base of stored procedures you may want to use a functionally oriented (not to be confused with functional languages) data access layer to wrap the incumbent sprocs. This re-uses the existing (and therefore tested and debugged) data access layer and database design, which often represents quite a substantial development and testing effort, and saves on having to migrate data to a new database model. It is often quite a good way wrapping Java layers around legacy PL/SQL code bases, or re-targeting rich client VB, Powerbuilder or Delphi apps with web interfaces.
A variation is where you inherit a data model that is not necessarily well suited to O-R mapping. If (for example) you are writing an interface that populates or extracts data from a foreign interface you may be better off working direclty with the database.
Financial applications or other types of systems where cross-system data integrity is important, particularly if you're using complex distributed transactions with two-phase commit. You may need to micromanage your transactions better than an ORM is capable of supporting.
High-performance applications where you want to really tune your database access. In this case, it may be preferable to work at a lower level.
Situations where you're using an incumbent data access mechanism like ADO.Net that's 'good enough' and playing nicely with the platform is of greater benefit than the ORM brings.
Sometimes data is just data - it may be the case (for example) that your application is working with 'transactions' rather than 'objects' and that this is a sensible view of the domain. An example of this might be a financials package where you've got transactions with configurable analysis fields. While the application itself may be built on an O-O platform, it is not tied to a single business domain model and may not be aware of much more than GL codes, accounts, document types and half a dozen analysis fields. In this case the application isn't aware of a business domain model as such and an object model (beyond the ledger structure itself) is not relevant to the application.
First off - using an ORM will not make your code any easier to test, nor will it necessarily provide any advantages in a Continuous Integration scenerio.
In my experience, whilst using an ORM can increase the speed of development, the biggest issues you need to address are:
Testing your code
Maintaining your code
The solutions to these are:
Make your code testable (using SOLID principles)
Write automated tests for as much of the code as possible
Run the automated tests as often as possible
Coming to your question, the two objections you list seem more like ignorance than anything else.
Not being able to write SELECT queries by hand (which, I presume, is why the copy-paste is needed) seems to indicate that there's a urgent need for some SQL training.
There are two reasons why I'd not use an ORM:
It is strictly forbidden by the company's policy (in which case I'd go work somewhere else)
The project is extremely data intensive and using vendor specific solutions (like BulkInsert) makes more sense.
The usual rebuffs about ORMs (NHibernate in particular) are:
Speed
There is no reason why using an ORM would be any slower than hand coded Data Access. In fact, because of the caching and optimisations built into it, it can be quicker.
A good ORM will produce a repeatable set of queries for which you can optimise your schema.
A good ORM will also allow efficient retrieval of associated data using various fetching strategies.
Complexity
With regards to complexity, using an ORM means less code, which generally means less complexity.
Many people using hand-written (or code generated) data access find themselves writing their own framework over "low-level" data access libraries (like writing helper methods for ADO.Net). These equate to more complexity, and, worse yet, they're rarely well documented, or well tested.
If you are looking specifically at NHibernate, then tools like Fluent NHibernate and Linq To NHibernate also soften the learning curve.
The thing that gets me about the whole ORM debate is that the same people who claim that using an ORM will be too hard/slow/whatever are the very same people who are more than happy using Linq To Sql or Typed Datasets. Whilst the Linq To Sql is a big step in the right direction, it's still light years behind where some of the open source ORMs are. However, the frameworks for both Typed Datasets and for Linq To Sql is still hugely complex, and using them to go too far of the (Table=Class) + (basic CRUD) is stupidly difficult.
My advice is that if, at the end of the day, you can't get an ORM, then make sure that your data access is separated from the rest of the code, and that you you follow the Gang Of Four's advice of coding to an interface. Also, get a Dependancy Injection framework to do the wiring up.
(How's that for a rant?)
There are a wide range of common problems for which ORM tools like Hibernate are a god-send, and a few where it is a hindrance. I don't know enough about your project to know which it is.
One of Hibernate's strong points is that you get to say things only 3 times: every property is mentioned in the class, the .hbm.xml file, and the database. With SQL queries, your properties are in the class, the database, the select statements, the insert statements, the update statements, the delete statements, and all the marshalling and unmarshalling code supporting your SQL queries! This can get messy fast. On the other hand, you know how it works. You can debug it. It's all right there in your own persistence layer, not buried in the bowels of a 3rd party tool.
Hibernate could be a poster-child for Spolsky's Law of Leaky Abstractions. Get a little bit off the beaten path, and you need to know deep internal workings of the tool. It can be very annoying when you know you could have fixed the SQL in minutes, but instead you are spending hours trying to cajole your dang tool into generating reasonable SQL. Debugging is sometimes a nightmare, but it's hard to convince people who have not been there.
EDIT: You might want to look into iBatis.NET if they are not going to be turned around about NHibernate and they want control over their SQL queries.
EDIT 2: Here's the big red flag, though: "Good practices, which are seen as pretty normal on Stack Overflow, such as unit testing or continuous integration, are non-existing here up to now." So, these "experienced" developers, what are they experienced in developing? Their job security? It sounds like you might be among people who are not particularly interested in the field, so don't let them kill your interest. You need to be the balance. Put up a fight.
There's been an explosion of growth with ORMs in recent years and your more experienced coworkers may still be thinking in the "every database call should be through a stored procedure" mentality.
Why would an ORM make things harder to debug? You'll get the same result whether it comes from a stored proc or from the ORM.
I guess the only real detriment that I can think of with an ORM is that the security model is a little less flexible.
EDIT: I just re-read your question and it looks they are copy and pasting the queries into inline sql. This makes the security model the same as an ORM, so there would be absolutely no advantage over this approach over an ORM. If they are using unparametrized queries then it would actually be a security risk.
I worked on one project where not using an ORM was very successfully. It was a project that
Had to be horizontally scalealbe from the start
Had to be developed quickly
Had a relatively simple domain model
The time that it would have taken to get NHibernate to work in a horizontally partitioned structure would have been much longer than the time that it took to develop a super simple datamapper that was aware of our partitioning scheme...
So, in 90% of projects that I have worked on an ORM has been an invaluable help. But there are some very specific circumstances where I can see not using an ORM as being best.
Let me first say that ORMs can make your development life easier if integrated properly, but there are a handful of problems where the ORM can actually prevent you from achieving your stated requirements and goals.
I have found that when designing systems that have heavy performance requirements that I am often challenged to find ways to make the system more performant. Many times, I end up with a solution that has a heavy write performance profile (meaning we're writing data a lot more than we're reading data). In these cases, I want to take advantage of the facilities the database platform offers to me in order to reach our performance goals (it's OLTP, not OLAP). So if I'm using SQL Server and I know I have a lot of data to write, why wouldn't I use a bulk insert... well, as you may have already discovered, most ORMS (I don't know if even a single one does) do not have the ability to take advantage of platform specific advantages like bulk insert.
You should know that you can blend the ORM and non-ORM techniques. I've just found that there are a handful of edge cases where ORMs can not support your requirements and you have to work around them for those cases.
For a non-trivial database based enterprise application, there really is no justifying not using an ORM.
Features aside:
By not using an ORM, you are solving a problem that has already
solved repeatedly by large communities or companies with significant
resources.
By using an ORM, the core piece of your data access layer benefits
from the debugging efforts of that community or company.
To put some perspective in the argument, consider the advantages of using ADO.NET vs. writing the code to parse the tabular data stream oneself.
I have seen ignorance of how to use an ORM justify a developer's disdain for ORMs For example: eager loading (something I noticed you didn't mention). Imagine you want to retrieve a customer and all of their orders, and for those all of the order detail items. If you rely on lazy loading only, you will walk away from your ORM experience with the opinion: "ORMs are slow." If you learn how to use eager loading, you will do in 2 minutes with 5 lines of code, what your colleagues will take a half a day to implement: one query to the database and binding the results to a hierarchy of objects. Another example would be the pain of manually writing SQL queries to implement paging.
The possible exception to using an ORM would be if that application were an ORM framework designed to apply specialized business logic abstractions, and designed to be reused on multiple projects. Even if that were the case, however, you would get faster adoption by enhancing an existing ORM with those abstractions.
Do not let the experience of your senior team members drag you in the opposite direction of the evolution of computer science. I have been developing professionally for 23 years, and one of the constants is the disdain for the new by the old-school. ORMs are to SQL as the C language was to assembly, and you can bet that the equivalents to C++ and C# are on their way. One line of new-school code equals 20 lines of old-school.
When you need to update 50000000 records. Set a flag or whatever.
Try doing this using an ORM without calling a stored procedure or native SQL commands..
Update 1 : Try also retrieving one record with only a few of its fields. (When you have a very "wide" table). Or a scalar result. ORMs suck at this too.
UPDATE 2 : It seems that EF 5.0 beta promises batch updates but this is very hot news (2012, January)
I think there are many good reasons to not use an ORM. First and foremost, I'm a .NET developer and I like to stick within what the wonderful .NET framework has already provided to me. It does everything I possibly need it to. By doing this, you stay with a more standard approach, and thus there is a much better chance of any other developer working on the same project down the road being able to pick up what's there and run with it. The data access capabilities already provided by Microsoft are quite ample, there's no reason to discard them.
I've been a professional developer for 10 years, lead multiple very successful million+ dollar projects, and I have never once written an application that needed to be able to switch to any database. Why would you ever want a client to do this? Plan carefully, pick the right database for what you need, and stick with it. Personally SQL Server has been able to do anything I've ever needed to do. It's easy and it works great. There's even a free version that supports up to 10GB data. Oh, and it works awesome with .NET.
I have recently had to start working on several projects that use an ORM as the datalayer. I think it's bad, and something extra I had to learn how to use for no reason whatsoever. In the insanely rare circumstance the customer did need to change databases, I could have easily reworked the entire datalayer in less time than I've spent fooling with the ORM providers.
Honestly I think there is one real use for an ORM: If you're building an application like SAP that really does need the ability to run on multiple databases. Otherwise as a solution provider, I tell my clients this application is designed to run on this database and that is how it is. Once again, after 10 years and a countless number of applications, this has never been a problem.
Otherwise I think ORMs are for developers that don't understand less is more, and think the more cool 3rd party tools they use in their app, the better their app will be. I'll leave things like this to the die hard uber geeks while I crank out much more great software in the meantime that any developer can pick up and immediately be productive with.
I think that maybe when you work on bigger systems you can use a code generator tool like CodeSmith instead of a ORM... I recently found this: Cooperator Framework which generates SQL Server Stored Procedures and also generates your business entities, mappers, gateways, lazyload and all that stuff in C#...check it out...it was written by a team here in Argentina...
I think it's in the middle between coding the entire data access layer and use a ORM...
Personally, i have (until recently) opposed to use an ORM, and used to get by with writing a data access layer encapsulating all the SQL commands. The main objection to ORMs was that I didn't trust the ORM implementation to write exactly the right SQL. And, judging by the ORMs i used to see (mostly PHP libraries), i think i was totally right.
Now, most of my web development is using Django, and i found the included ORM really convenient, and since the data model is expressed first in their terms, and only later in SQL, it does work perfectly for my needs. I'm sure it wouldn't be too hard to outgrow it and need to supplement with hand-written SQL; but for CRUD access is more than enough.
I don't know about NHibernate; but i guess it's also "good enough" for most of what you need. But if other coders don't trust it; it will be a prime suspect on every data-related bug, making verification more tedious.
You could try to introduce it gradually in your workplace, focus first on small 'obvious' applications, like simple data access. After a while, it might be used on prototypes, and it might not be replaced...
If it is an OLAP database (e.g. static, read-only data used for reporting/analytics, etc.) then implementing an ORM framework is not appropriate. Instead, using the database's native data access functionality such as stored procedures would be preferable. ORMs are better suited for transactional (OLTP) systems.
Runtime performance is the only real downside I can think of but I think that's more than a fair trade-off for the time ORM saves you developing/testing/etc. And in most cases you should be able to locate data bottlenecks and alter your object structures to be more efficient.
I haven't used Hibernate before but one thing I have noticed with a few "off-the-shelf" ORM solutions is a lack of flexibility. I'm sure this depends on which you go with and what you need to do with it.
There are two aspects of ORMs that are worrisome. First, they are code written by someone else, sometimes closed source, sometimes open source but huge in scope. Second, they copy the data.
The first problem causes two issues. You are relying on outsiders code. We all do this, but the choice to do so should not be taken lightly. And what if it doesn't do what you need? When will you discover this? You live inside the box that your ORM draws for you.
The second problem is one of two phase commit. The relational database is being copied to a object model. You change the object model and it is supposed to update the database. This is a two phase commit and not the easiest thing to debug.
I suggest this reading for a list of the downsides of ORMs.
http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx
For my self, I've found ORMs very useful for most applications I've written!
/Asger
The experience I've had with Hibernate is that its semantics are subtle, and when there's problems, it's a bit hard to understand what's going wrong under the hood. I've heard from a friend that often one starts with Criteria, then needs a bit more flexibility and needs HQL, and later notices that after all, raw SQL is needed (for example, Hibernate doesn't have union AFAIK).
Also with ORM, people easily tend to overuse existing mappings/models, which leads to that there's an object with lots of attributes that aren't initiliazed. So after the query, inside transaction Hibernate makes additional data fetching, which leads to potential slow down. Also sadly, the hibernate model object is sometimes leaked into the view architecture layer, and then we see LazyInitializationExceptions.
To use ORM, one should really understand it. Unfortunately one gets easily impression that it's easy while it's not.
Not to be an answer per se, I want to rephrase a quote I've heard recently. "A good ORM is like a Yeti, everyone talks about one but no one sees it."
Whenever I put my hands on an ORM, I usually find myself struggling with the problems/limitations of that ORM. At the end, yes it does what I want and it was written somewhere in that lousy documentation but I find myself losing another hour I will never get. Anyone who used nhibernate, then fluent nhibernate on postgresql would understand what I've been thru. Constant feeling of "this code is not under my control" really sucks.
I don't point fingers or say they're bad, but I started thinking of what I'm giving away just to automate CRUD in a single expression. Nowadays I think I should use ORM's less, maybe create or find a solution that enables db operations at minimum. But it's just me. I believe some things are wrong in this ORM arena but I'm not skilled enough to express it what not.
I think that using an ORM is still a good idea. Especially considering the situation you give. It sounds by your post you are the more experienced when it comes to the db access strategies, and I would bring up using an ORM.
There is no argument for #1 as copying and pasting queries and hardcoding in text gives no flexibility, and for #2 most orm's will wrap the original exception, will allow tracing the queries generated, etc, so debugging isnt rocket science either.
As for validation, using an ORM will also usually allow much easier time developing validation strategies, on top of any built in validation.
Writing your own framework can be laborious, and often things get missed.
EDIT: I wanted to make one more point. If your company adopts an ORM strategy, that further enhances its value, as you will develop guidelines and practices for using and implementing and everyone will further enhance their knowledge of the framework chosen, mitigating one of the issues you brought up. Also, you will learn what works and what doesnt when situations arise, and in the end it will save lots of time and effort.
Every ORM, even a "good one", comes saddled with a certain number of assumptions that are related to the underlying mechanics that the software uses to pass data back and forth between your application layer and your data store.
I have found that for moderately sophisticated application, that working around those assumptions usually takes me more time than simply writing a more straightfoward solution such as: query the data, and manually instantiate new entities.
In particular, you are likely to run into hitches as soon as you employ multi-column keys or other moderately-complex relationships that fall just outside the scope of the handy examples that your ORM provided you when you downloaded the code.
I concede that for certain types of applications, particularly those that have a very large number of database tables, or dynamically-generated database tables, that the auto-magic process of an ORM can be useful.
Otherwise, to hell with ORMs. I now consider them to basically be a fad.

Categories

Resources