A single place in NHibernate and Sharp Architecture to specify field length for database and validation - nhibernate

I'm building a new system with NHibernate, using S#arp Architecture. I'm new to S#arp, but experienced with NHibernate. One feature I was really hoping to find was a nice way to specify in one place text field lengths that would be carried through to every layer that needs to know the length.
In other words, I use Fluent mapping to specify that the Name field of a Whatsis object is 50 characters. (I turned off automapping because I was still writing mapping overrides for most, if not all classes. I decided just to write the full mapping myself with ClassMap. I want enough detail in the mapping to generate the complete DB schema from it.) Then when I generate the database schema using hbm2ddl, I get a 50-character field length. That's great. But I also want the MVC validators to enforce it automatically. And I'm so greedy I even want the proxy object the NHibernate generates for Whatsis to know about that length in its setter, so if in code I should assign a too-long value, I'll get an exception.
Do I have any hope of achieving this without really overcomplicating my project? This is my first time using Fluent mapping. I thought this was a feature of Fluent, but it looks like it doesn't work that way after all.

You need to use NHibernate Validator as that is the only validator framework that NHibernate hbm2ddl currently supports. Unfortunately it doesn't look like anyone has wired together NHibernate Validator and MVC3 validations. Here is someone else having problems with it:
MVC 3, NHIbernate Validators & Message Interpolator
It should be possible as I've used xVal (predecessor to MVC3 validators) in the past with NHibernate Validator attributes for client-side validation, server-side validation, and schema generation. Someone just needs to invest some TLC to get NHibernate Validator playing nicely with MVC3 validators.

Related

Automatically generating poco classes

Today I was checking out a few technologies: T4 templating, automapper
some mini orms: petapoco, sqlfu, ormlite
I understand the gist of what these technologies provide. I'm currently working on a 3 tier system, and I would have loved to replace the DAL (data access layer located on it's own data server) and have it integrated with a mini ORM as shown. However, I will be making no such plans for now. We currently use .NET Remoting (predates WCF).
So instead of replacing whatever is on the DataServer, I'd like to extend one of these new technologies on the application server.
I've done research on how Entity Framework can automatically generate POCO classes based on the context, which is done manually after building EF, I was wondering if I can do the same without using EF.
So here's the facts on what's currently happening:
Send a sql statement (or stored proc) to the DAL to execute
Retrieves a DataSet or a DataTable back to the application through TCP channel
My question is, is it possible to automatically generate a dynamic POCO class using keywords "var" and "dynamic" based on the values sent back from the DataSet and do dynamic mapping onto it during runtime? Would any of the technologies mentioned above help? Or do I have to manually create the POCO class first, and do a mapping on it?
It seems a bit redundant for me to manually create a POCO class and map it to a backend sql table if the application could be aware of what the POCO class is supposed to have. Like what happens if I update a table on the backend, then I'd have to update the POCO class associated with it as well. I'd love to have this to be automatic for me.
If you know the data sets at compile time, then T4 might be an option. You can write a T4 script that downloads the database schema, and constructs strongly-typed entity classes and database reads/write methods.
As far late-bound (runtime) classes, one option is to use the runtime typing provided by CustomTypeDescriptor. You can pass arrays of objects back and forth from the server, and use reflection or other techniques to infer the type.
I think it should be clear that #1 is preferable, if you know the types at compile time (which it sounds like in your case here). Runtime and dynamic should only be a last resort, as it circumvents a lot of valuable compile-time type checks.
Really, I would recommend using one of the micro ORMs like Dapper, etc, if you don't want to use the full Entity Framework. That is, unless you really want to re-invent the wheel.

NHibernate Database-First

I'm putting a front-end together for one of our databases and would like to use NHibernate for it.
Can anyone point out any resources for getting started with Database-first approach? Most tutorials I've seen are for Code/Entity First.
ASP.NET MVC 3 will be my environment, if it matters.
Thanks.
It is all about configuring with NHibernate. As long as Nhibernate is concern, it will not create a database if that is not exists. So you have to configure Nhibernate with the connection string of your existing database in hibernate.cfg.xml(You can also use loquacious api)
There are lots of configuration possibility in NHibernate; Example includes ConfORM, FluentNhibernate, Configuring With Code, XML.
For existing database going with xml is often easy. If you choose xml, you can use tools like myGeneration to generate mappings for you.
As long as you map your object correctly with the existing database nibernate will not complain whether you create your database first or code first. So any intorductory example/application/resource that uses nhibernate as an orm mapper should serve as getting started for you.
Still there are some techniques you can follow to do database first modeling. Here is a link that may help(code example) Effective Techniques for Database-Driven Modeling
Here is the Screen Cast Explaining the techniques
please take a look at this: http://www.devart.com/entitydeveloper/nhibernate-designer.html it is not a freeware.
There is another open source tool which was referred in another question long time back. here is the link: http://www.mygenerationsoftware.com/phpBB2/viewtopic.php?t=1505
btw are you planning to use fluent nhibenrate or just nhibernate?
On a side note: Entity Framework supports a database-first approach with an integrated designer for Visual Studio. This designer produces an XML file (EDMX) that describes the required mappings.
Note: I am not marketing any of these products.

nhibernate architecture

Hello
I want to create my first nhibernate projet.
It will be a migration from a winform project associated with an old dataacess with no strong orm mapping.
The project is quite large so I'd like to have a good architecture from the beginning.
I will have some layer :
Repository : Create the session from nhibernate
Model : The bean object, basically it consists of getter / setter properties with the same name in the database
But I'll need some advices, how will you handle the operations ?
If I want to create an item should I access directly to nhibernate from the code ? Or should I create a business logic layer ?
Basically I found that simple architecture for the business layer.
http://www.codeproject.com/KB/architecture/NHibernateArchitecture.aspx
What is your feeling ?
Another question, it is a program with strong validation (glasses domain), where should be the validation ? in the winform project or in a business layer ?
It's hard to say and give useful advices without seeing the project and its actual problems. Is it client-server architecture for instance? What do you mean by "quite large"? There are too many different projects to have rules which fit all.
Generally:
In most of the cases, it is very useful to have a business layer.
validation should be in the business layer. There is also NHibernate validation and some other validation frameworks around, which allow declarative validation.
The most common mistake I see when starting with NH is that people don't understand persistence ignorance. This means that you should write your business logic without accessing the database or NH. Changes are made on the entities, they are not "temporarily" until they get explicitly applied to the database, they get implicitly stored when the transaction gets committed. This has a huge impact to the code. In many cases, there is no "Store" or "Update" or whatever.
Take a look at SharpArchitecture. It is a very good framework for NHibernate. Very good example on how to wire everything up.
http://www.sharparchitecture.net/

How could nHibernate not be 100% compile time tested?

One thing that bothers me about nHibernate is that it is not 100% compile time tested.
If I rename a column in my database table, and I update the mapping file for that table, when I hit compile I should get errors in all my query code (hql/criteria whatever) of where I referenced that column name and how it is spelled wrong.
The whole point (for me anyway) of using an ORM was that database changes won't break my queries.
In other words, I will be notified at compile time of what needs to be fixed, instead of getting runtime errors etc.
To achieve what you want I think your best solution is to use a combination of Fluent NHibernate and nhlambdaextensions. Fluent NHibernate will give you type-safe checking on your mapping files (so if you change a property on your entity, the compiler will throw an error if you don't also change the property on your mapping class). The lambda function extensions will give you type-safe queries via the Criteria API (not HQL since that's just magic-strings SQL-with-objects).
Also to clarify your question, you said:
If I change a column (rename) in my
database table, and I update the
mapping file for that table, when I
hit compile I should get errors in all
my query code (hql/criteria whatever)
of where I referenced that column name
and how it is spelled wrong.
Just changing the database side should break nothing (assuming you also make the change in your XML mapping file). Your code does not reference the column="first_name" portion of the mapping, it references the name="FirstName" portion. If you do not change your entity, renaming a column (from "firstname" to "first_name", for example) in the database will not break your queries as long as you update your mapping file as well.
You should look at Castle ActiveRecord. I used this before and it allows you to not worry about the mapping files (.hml) as much. It lets you make your changes at the class level definitions, and the mappings files were generally untouched.
If you are writing bad queries, that sounds like a design problem, not an nHibernate problem.
You won't get errors providing the Property names haven't changed, as most people use HQL for their queries in NHibernate.However if you do change the Property names and not the HQL you will indeed get broken queries, e.g.:
FROM User Where User.Surname = 'bob'
Change the Surname property to Lastname and it'll break. It's a feature lacking in NHibernate but would make a good project for the contrib - a Subsonic style query interface. This a project sort of similar but still use HQL.
As mentioned above ActiveRecord and Fluent NHibernate are the closest to type checking with NHibernate. Both enforce that you inherit your classes from their base class, as you'd expect and ActiveRecord is not intended for production use - Ayende has said in a video that's meant to be a prototyping tool for NHibernate.
Hibernate uses dynamic byte code generation to create the mapping classes, based on the mapping configurations.
The fundamental point of ORM is to enable auto-magical mapping (bridge) between Objects and Relational systems. Thus: ORM.
if you want to strongly type your objects rather than using xml config which can cause alot of runtime issues if not properly tested, I would look into FluentNHibernate which has convention maps that allow you to map your classes to data in code. Made my life alot easier especially when first starting with NHibernate wish i had found it before i knew how to properly map using xml
Does NHibernate have the equivalent of the Java version's schema validator? In which case, you could add a step to your build process to build the session factory and run the validator-- building the session factory should also compile named queries, hence validating them too.
Hmm, looks like it supports something like that: http://nhibernate.info/blog/2008/11/22/nhibernate-schemavalidator.html
NB this means your build process will fail to work if your dev database is not available--- which I would regard as a bad thing.

NHibernate or FluentNHibernate or ActiveRecord?

I am in a stage of mapping my CSharp classes into database tables. I have decided to use NHibernate as my ORM tool after comparing with other tools. I have never done a real project with NHibernate before and now am considering alternatives for the mapping,
ActiveRecord: according to the project's web site, using ActiveRecord can boost productivity dramatically. However, I do not like the idea of adding attributes to my CSharp classes. After all, my class should NOT have any knowledge of database relationships. By using ActiveRecord will bind my nicely separated classes to ActiveRecord, and give me hard time if I ever want to switch underline DAO Layer implementation in the future.
FluentNHibernate: FluentNhibernate was my first attempt when starting mapping. But I also have a few issues with this approach. 1) I don't like my mapping strategies compiled as binary files. I would like to be able to change mapping by modifying xml files. 2) The maturity of FluentNHibernate. NHibernate has been around for a long time, and has LOTS of users, so I am quite comfortable with its maturity. On the contrast, FluentNhibernate is relatively young and not been tested by as many users. Even though I could dive into the source to fix whatever issue comes up, I am not comfortable with my skills to touch the low level implementation. 3) Availability of documentation for FluentNHibernate is much than that of NHibernate. I would like to have a place to go when I hit a hard wall.
NHibernate: Currently, I am using naked Nhibernate xml to do the mapping. To be honest, working with XML gives me massive headaches. Literally, I have to keep myself from the impulsion of just throwing away the .hbm.xml files and grab ActiveRecord or FluentNHibernate several times a day.
So, here is my dilemma: Should I go with my heart of "Just get this damn thing done!"; Or, should I follow the "Good practice guideline" to suffer the pain now and get relatively easy time later on?
Any comments?
Please note that any classes related to an ORM should not necessary be treated as "business object" classes or exposed to your UI. They should be considered part of your data layer. This pattern is not really unique to ActiveRecord. In general, you want your business layer to know as little as possible regarding the fact that there is an ORM beneath it, and you don't want your UI to know about your data layer. You also want to consider DTOs.
Fluent NHibernate solves the problem of having weakly typed XML which can be error prone to refactor.
While there can be downsides of adopting something like ActiveRecord, it seems like an appropriate solution in your case.
The best reason to use .hbm.xml files is if you are going to code generate them from your database (using something like CodeSmith). Hand coding the .hbm.xml files is rarely the best option.