Getting Started with Fluent NHibernate - fluent-nhibernate

I'm trying to get into using Fluent NHibernate, and I have a couple questions. I'm finding the documentation to be lacking.
I understand that Fluent NHibernate / NHibernate allows you to auto-generate a database schema. Do people usually only do this for Test/Dev databases? Or is that OK to do for a production database? If it's ok for production, how do you make sure that you're not blowing away production data every time you run your app?
Once the database schema is already created, and you have production data, when new tables/columns/etc. need to be added to the Test and/or Production database, do people allow NHibernate to do this, or should this be done manually?
Is there any REALLY GOOD documentation on Fluent NHibernate? (Please don't point me to the wiki because in following along with the "Your first project" code building it myself, I was getting run-time errors because they forget to tell you to add a reference. Not cool.)
Thanks,
Andy

I've been using Fluent NHibernate Automapping for a few months now. I'm by no means an expert, but can take a stab at your questions...
FNH Automapping does indeed create DB schemas from POCO classes, including lists of other objects (this was the reason I chose NHibernate in the first place).
When you change schemas, you have to rerun the automapping, which does drop the whole database, unfortunately. In my case, it's not a big problem because I'm importing existing binary data files, so I just have to re-import my data every time the schema changes. I've read that there's some data migration support available with NHibernate, but have no experience with this. (BTW, Subsonic will do data migration, but it's automapping functionality is far more rudimentary - at least it was when I evaluated it a few months ago)
FNH documentation is one of my pet peeves - they have not even added Intellisense help on the method names, etc. (But they get really huffy when you point that out - ask me how I know!) I've made a couple of edits to the wiki when I could, but there's so much more that could be done there. The best approach is to start with a working example (i.e.
this one from Nikola Malovic, and post questions to the support form if (when!) you run into trouble. In general, I've found the FNH community pretty helpful, and have been able to work through all my difficulties. They've also fixed a couple of bugs I've found.
Overall, using FNH has been a huge win for my project - highly recommended!

I don't use Fluent, but I can help with classic NHibernate.
yes, the creation of the schema is very recommendable for production use (Schema Export). When you do this is up to you. For instance, you could create the database by an installer. You shouldn't drop existing databases, but this is a decision of you application.
I don't understand this question. Do you mean you need to upgrade an existing database to a new database schema? This is unfortunately something you need to implement yourself. NH can't do much about this, because it is very specific to you data and the changes you made. There is also a Schema Update or something like this, which is not recommended for production use.
I don't use Fluent, so I can't help here.

Related

Audit trail techniques

My project is in ASP.NET MVC3, SQL Server 2008 and using Fluent NHibernate.
I now have a requirement to audit certain properties of a specific object.
i.e. recording the old and new value of the properties changed on that object and also create and delete events on the object itself.
I think there can be several ways to approach this task - database triggers, INotifyPropertyChanged interface, or any NHibernate provided features?
Alternatively any open source libraries that will make my life simpler.
However, what i am not sure about is which path to choose. I mean this is a very vast area where I can go on exploring and still can't come to any conclusion.
It will be really helpful if I can get some guidance as to which option will be best considering my requirement and I can look into it more from there.
Thanks a lot.
Maybe I'm a bit biased but...
Have you had a look at Envers? https://bitbucket.org/RogerKratz/nhibernate.envers

Which ORM frameworks will build and execute the SQL DDL for you?

Entity Framework Code First will build the database for you if it doesn't exist and structure it based on your mapping objects. I believe Roundhouse will do the same thing with Fluent Mapping files using NHibernate.
Are there any other ORM's (or tools like Roundhouse) that will take care of all your SQL DDL creation and execution?
NHibernate does not need Fluent Mappings to generate database schema. This feature is built into the NHibernate core:
new SchemaExport(_configuration).Execute(false, true, false);
In my experience however this is mostly useful for in-memory integration tests or initial rollouts. Production databases need to be upgraded. If you stick around, then you will need to add and remove columns, tables and foreign keys without affecting data. There is a continuity and versioning aspect to it. NHibernate only knows your current mapping. It does not know for example that 2 months ago you stored your customer first and last name in column called "CustomerName" and then you decided to split this into two columns "FirstName" and "LastName" (which is probably the most primitive change that can be made). NHibernate job is to map your current schema to objects, not to remember data modeling choices from few years ago.
In my experience there is no magic tool that will write upgrade scripts, they have to be written manually or at least reviewed by developer. Tools can provide you a framework for executing these scripts, like RoundhouseE. Scott Allen has an excellent series about 'forward-only, run-once' approach.
hibernate does if you set hbm2ddl.auto to create or create-drop or update in the config file. Using Java that is, I assume its the same for nHibernate.
If an ORM does not do ddl, there is not much point in having it, well its a key feature at least. Imho.

How does EF4 compare with NHibernate?

Is it any better? I heard the CodeFirst extension but is it ready for primetime. Please share your experience with development, any performance overheads, etc.
I think this is a timely question, as I was wondering the exact same thing. I am trying to create a serious e-commerce model and I am trying to keep my POCOs free of persistence concerns as well as trying to stay true to Domain Driven Design. So far, I am very wary, and I am on the fence about whether I should jump ship to NHibernate. The only thing keeping me from doing so is that I assume that Microsoft will improve (and quickly).
Some of the biggest problems so far:
Inability to finely control object materialization. EF calls the zero-arg constructor on your POCO, and this is a behavior you cannot change.
No enum support. The community has been screaming -- screaming! -- for this, and it hasn't happened. The workarounds are terrible, and pollute your domain model.
Weird mapping bugs when trying to control column names and relationships in the database. The main ones I can think of are with compound keys and many-to-many relationships. These can be worked around, and I assume these will be fixed by release time, but they are frustrating nonetheless.
Bad SQL. I also do DBA work, and the SQL that EF generates (with or without Code-First) is atrocious.
And this is just the tip of the iceberg: I am only starting to learn EF4 and I'm running into awful roadblocks. As I think of more reasons, I'll add them here. I'm still struggling through it.
(I wonder whether the community will give it another vote of "no confidence.")
More:
To add to the "Weird mapping bugs" problem: You cannot control the name of a column if it participates in a self-referencing relationship (for example, if you have a hierarchy). I assume this will be fixed in the final release.
Lack of batching, resulting in multiple roundtrips to the database. For example, how do you delete a bunch of items from a collection? Load all entities into memory and delete them one at a time. A smaller gripe is the number of DB hits when inserting into tables that participate in an inheritance relationship.
No intelligent way to deal with model changes. EF Code-First loves to completely drop your entire database if it needs to change the schema.
Few extensibility points. You can literally count on one hand the number of events that EF4 allows you to subscribe to (and Code-First doesn't provide much more).
As for me - I prefer EF but with some enhancements. Basically EF offers to you the following advantages:
Visual Model Editor
Database/Model Update wizard (instead of manual XML changes - what is terrible for me)
Also, I'm using 3-rd party commercial tools based on EF and L2S (LinqConnect) that provide for me the following features:
Geography support
Optimized SQL generation
Product absolutely integrated to Visual Studio
Smart database update wizard (synchronization mode)

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.