When working with NHibernate, should you create your database tables before your map files? - nhibernate

Simple question, hopefully with a simple answer. I was under the impression I should create my tables and then use the map files to map my POCO classes to the database objects. After following some tutorials, I have this code in my Test SetUp:
new SchemaExport(_configuration).Execute(false, true, false, false);
Which, obviously, create the table structure as defined in the mappings, so I'm confused.

You need the mapping files for SchemaExport.
Ideally you write / design your classes first, write the mapping files afterwards. When writing mapping files, you are designing the database tables at the same time. SchemaExport just creates the schema from the mapping files where all the information is usually available.
SchemaExport is highly recommendable, even if it is a bit "hidden" in the docs.

It is better to have only one place to change, in your case you make changes in your classes and your db is automagically updated - do you expect anything better?
Sometimes you write new code for existing database, so you have to create (or have) database first, then need to prepare mappings manually.
EDIT:
I am using Fluent NHibernate, so this can be done fully automatically, not sure in different environments.

Related

Solution For Updating LINQ to SQL Files After Database Schema Change

I recently started using LINQ to SQL in my database later for a C# Windows Forms project. Until now, I have been very impressed with how fast I have been able to implement the data access layer. The problem that I am facing is similar to the post from 2008 below
Best way to update LINQ to SQL classes after database schema change
In short, I am struggling to find an efficient solution for updating the LINQ to SQL files after making minor changes to the database such as constraints, foreign keys, new columns, etc...
Thus far, I have merely been deleting the tables in the LINQ to SQL designer and dragging them back onto the designer. However, I now have the need to rename many of the associations in the designer. The problem is that each time I have to re-create the LINQ to SQL files I lose the change that I manually made to the files. Can someone tell me if there are any new solutions and/or methods for solving this problem. The post that I have included as well as many other dated sources of information mentions that SQLMetal and Huagati are good tools. Additionally, I have read that you can manually create your LINQ to SQL files rather than auto-generate them with the designer (this is what I had to do when using Hibernate with Java).
I know that manually creating the domain classes and mapping files will be consuming. I am not familiar with SQLMetal or Huagati. Can anyone recommend the most elegant or preferred way to deal with this issue? I know that I could use Entity Framework but, I have inherited this project and I am under a very tight deadline. I can refactor it to another Framework once I have this phase complete.
After much research and reading, I have determined that the best solution for updating my DBML after minor database changes is to manually edit the file. The procedure used to update the DBML is below:
Right-click on the DBML file
Open with XML Editor
Add or change the columns in the affected table
Add or change any associations
Save the DBML
Rebuild the project
This is not ideal but, once it has been done a few times it is pretty painless for the types of changes that I occasionally need to make to the database such as changing data types, adding keys, etc...
I don't touch dbml or linq2sql generated files because there is risk that my changes would be overwritten. I use only my generated partial classes. When database schema changes I remove old table from dbml-editor and pull new table to it.

NHibernate and code first

Do you use SchemaExport and SchemaUpdate in real applications? Initially, you create model and then generate schema? Does it work? Or, you use it only for tests...
Usually, I create db (using visual studio database project) and then mappings and persistent classes or EF entities using designer. But now, I want to try code first approach with Fluent NHibernate.
I have researched SchemaExport and SchemaUpdate and found some issues. For example, update doesn't delete db objects, creates not null columns like nullable if table exists, doesn't generate primary key on many-to-many tables and so on. It mean that I have to recreate db very often. But, what's about data? And, how to deploy changes to production db and so on...
I want to know do you really use code first and SchemaExport(SchemaUpdate) in your applications? May be you can give me some advices...
I use SchemaUpdate in production. It is safe precisely because it never does destructive operations like deleting columns. However, it is not a comprehensive solution for updating your database. If you use it you will still have to supplement it with script to update your schema to do things like deleting (as you mention), indexes, changing column type, adding table data, etc. But SchemaUpdate covers the 90% case for me.
The only downside I've discovered is that over time it seems to occasionally add duplicate foreign-key constraints to my table.
One more thing: you should run SchemaUpdate manually from a build tool, not your app itself. It is not safe to give your application the rights to modify your db schema!
I use SchemaUpdate/SchemaExport for rapid evolution of my model, but they are not a replacement for a database migration tool. As you mention, data cannot be migrated in a sensible manner in many cases. The tool does not have enough context. (e.g. How can you automatically migrate a FullName column to FirstName/LastName?) I answered a similar question here where I discuss db migration tools in the context of NHibernate.
NHibernate, ORM : how is refactoring handled? existing data?
Yes, you can use these in real applications; I do.
Of course, almost all the work happens in that first go. My practice has been to create a separate project that references the mappings in my main project assembly and handles database creation and the initial data import, if any.
Once the project is in production, I usually unload that project from the solution, but keep it around for reference or if I ever need to switch from create scripts to update scripts.
As for the way NHibernate creates the database, you have to do a little more specification in your Fluent mappings than you otherwise might. I like to specify null/not null, foreign key constraint names, etc. to have maximum control over the way the database gets created.
I don't think you'd ever want to use automapping in this scenario.
Just with any generating code whether it be poco generation from a tool or database generation as in your question, it will probably get you 80% of the way there. From there it would be wise to tweak it the other 20% to add your indexes and any other performance tweaks to get it just right.

Using nHibernate to retrieve Database Schema

Is it possible to generate a schema of a database from nHibernate, where I have provided nHibernate with the configuration to the database but I have not written any mappings.
I wish to get the Database MetaData/Schema programmatically.
I am using an Oracle Database. I have tried two approaches:
Approach one:
public DatabaseMetadata GetMetadata(DbConnection connectionIn)
{
return new DatabaseMetadata(connectionIn, _dialect);
}
Problem: This seems to be what I need however, although it correctly connects, it hasn't picked up any of my tables. All I provided was the nHibernate Configuration object which was populated with the contents of my nHibernate.xml.config file (connection string, driver client, etc).
Question: Why would it not return the table data? It's connected correctly but finds nothing!
Approach two:
public void DatabaseSchema()
{
var schema = new SchemaExport(nHibernateConfiguration);
schema.SetOutputFile("schema.dll");
schema.Create(true, true);
}
nHibernateConfiguration is an instance (property on class) of the nHibernate Configuration object, populated with contents from the nHibernate.xml.config class.
Problem: This simply doesn't work. Crashes with the following exception:
NHibernate.MappingException : Dialect
does not support identity key
generation
I suspect this will only generate a schema based on mappings you have created? I have created no mappings. The idea is this will work against whichever database I have connected to a generate a schema for it.
Question: Is my belief that this method will only generate a Schema based on my mappings? If not, Am I using it correctly?
Hopefully this is clear enough, comment if I need to provide more info.
Thanks In Advance.
To be clear: I have a database and want to get meta data representing the database, a schema.
NHibernate is actually based on the mapping files. You could generate classes or tables from them. There are tools to generate the mapping files, but they are based on the classes, not the tables.
Answers to your specific questions:
Approach one: NHibernate does not read table definitions from the database. All the table definitions need to be specified in the mapping files.
Approach two: SchemaExport creates an SQL file (Create tables, indexes etc) from the mapping definitions. It is actually recommended to use it, unless you need to cope with legacy databases. The output file should be called *.sql, not *.dll.
The error you get is most probably because you try to create an identity id on an oracle database (or another which does not support identity columns). Use hilo instead (or, if you don't like it, guid.comb or native). I just wonder why you get this error, I thought that you didn't write any mapping files?
Conclusion:
I don't know of any tool which create NHibernate mapping files from database tables. There may be one, most probably it is not free or not mature (because otherwise it would be well known). So I suggest to think about generating the table definitions instead, or, in case you have a legacy database, you need to go through writing the mapping files manually.
There are several tools to help you out but the two I use the most are the following two.
NHibernate Schema Tool
NHibernate Mapping Generator
If you already have a schema you can use the NHibernate Mapping Generator to create your mappings. You can then use the mappings for whatever you want. Modify them and use NHibernate Schema Tool to manage the actual schema.
If you don't have any schema and that is what you are trying to create you are on the right track. First you need to "map" your classes. Preferably using Fluent NHibernate or ConfORM like Michael Maddox suggested.
I don't know the purpose of this. If it is database schema management I would recommend against using NHibernate. NHibernate was never developed as a schema manager tool so it probably should not be used this way. Admittedly I might have misunderstood you somehow and this answer could be completely wrong.
I may be interpreting the question wrong, it's not really clear what you are asking for.
Assuming you have created classes and configured NHibernate correctly and you want to create tables in the database for those classes, you have at least two potential ways to try to generate a database without creating NHibernate mappings, both of which will likely work much better with at least some hints about how to do the mappings:
Fluent NHibernate Automapper
ConfORM
There is a decent learning curve for both options.
Another option is to try one of the commercial visual designers for NHibernate, although those tools aren't quite mature enough to do this really well in my experience.
Core NHibernate is not designed or intended to create tables without mappings files.

Using Schema Export Efficiently

We are using NHibernate as our ORM framework.
We have a need to persist classes we load at run time. We do that according to metadata they come with, that holds names and types of the data they have.
In order to build the tables for them at run time, we use the SchemaExport class from the NHibernate ToolSet API.
We wanted to ask two questions:
Is there a way to make NHibernate do all the actual creations in one roundtrip to the DB instead of a roundtrip per table?
In order to use the SchemaExport tool are building a dynamic string that represents a mapping file from a template we keep. Is there a better way to do this? Maybe even without a mapping string?
Ad 2.
If I understand you correctly, you don't want to use hbm mappings, right? Have you considered using Fluent NHibernate? (http://fluentnhibernate.org/)

How can I generate "migration" DDL from NHibernate mapping files?

I'm using NHibernate 2 and PostgreSQL in my project. SchemaExport class does a great job generating DDL scheme for database, but it's great until the first application.
Is there any way to generate "migration" DLL (batch of "ALTER TABLE"'s instead of DROP/CREATE pair) using NHibernate mapping files?
Look into SchemaUpdate. Very similiar API as SchemaExport but it only creates migrations.
While SchemaUpdate very much answers my needs, it still has several problems. For example it refuses to put a new restriction on existing database column even if it's not gonna conflict with existing data.
I'm going froward to extend SchemaUpdate a little bit or, if fail, switch to one of that hand driven migration tools (for example Rails one).