nhibernate architecture - nhibernate

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/

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.

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)

Designing layered app with NHibernate and context changing database

I'm designing a C# application
Presentation ( web site + flex apps )
Business Logical Layer (might be WCF to enable multi client platforms)
Data Access Layer ( With NHibernate )
We're going to integrate our solution in many preexistant client's database environnements and we would like to use NHibernate in the DAL.. My colleague pointed out that generating classes from client's DB (like User or Image) with NHibernate would cause the BLL to blow up in our face at each DB changes !
So the question is how do we prevent that from happening ?
We're thinking about creating business objects and map NHibernate objects to these BO (hum, does that make them DTOs ?) with AutoMapper and prevent dal changes from affecting BLL.. Is this the way to go ?
Thanks !
EDIT :
To give a better understanding of what we're trying to achieve, you might need context :
We're building a photo storing/sharing app in Flex for the front-end and C# on the back-end mainly for our company, so we handle every aspects of the code and DB.
But : that product can also be bought by tiers, which eventually have already a database with User table or Image table. I'm thinking here about a new prospect who have an Image table with a few hundred millions of rows and adding columns for our business logic isn't going to be happening because of a too long ALTERing of the table.
Even though it would be possible (User table for example can be modified because of lesser rows), we're asking ourselves how to handle table structure changes without impacting all of our solution each time we have to integrate in a tier database, from BLL to client app in Flex !
in my experience, your business objects (AKA Domain Objects) should be modelled in OO to represent your real life business entities and your tables in 3rd normal form (this may change depending on what design you are after speed vs file size)
NHibernate should map between your BO's and Tables, using its mapping files.
now you have legitimate cases:
You need to add/remove a column, we decided to remove addressline4, this will echo a change in your Address Object, thats fine.
You move a column to a better place, our Client object contains notes, which is currently stored in the Contract_Extra table, which is going to be moved into the Client table. moving the column into a better place will only effect the Mapping file, in this case
I doubt there is a blanket reasoning, however I hope the examples make you think about this
I have not tried NH accross multiple Db's, also should each database have its own service on top?
here are some links
Multi table entites
PoEAA <- look at the Single Table inheritance, Class table inheritance and the other one
Hope this helps
It sounds like you want to design your domain model to be database agnostic. I too am interested in the best approach to having a central domain model that can map over to multiple different database models.
The way you are proposing, to create DTO's from each database using code generators, could be an option. Another would be to create custom NHibernate mappings for each preexisting database. You still may need to use some DTOs to make some of the mappings less difficult but it may give you more control.
These are just some thoughts. More experienced users with NHibernate probably will have better insight to your situation.

Saving a single entity instead of the entire context - revisited

I’m looking for a way to have fine grained control over what is saved using Entity Framework, rather than the whole ObjectContext.SaveChanges(). My scenario is pretty straight forward, and I’m quite amazed not catered for in EF – pretty basic in NHibernate and all other data access paradigms I’ve seen. I’m generating a bunch of data (in a WPF UI) and allowing the user to fine tune what is proposed and choose what is actually committed to the database. For the proposed entities I’m:
getting a bunch of reference entities (eg languages) via my objectcontext,
creating the proposed entities and assigning these reference entities to them (as navigation properties), so by virtue of their relationship to the reference entities they’re implicitly added to the objectconext
Trying to create & save individual entites based on the proposed entities.
I figure this should be really simple & trivial but everything I’ve tried I’ve hit a brick wall, either I set up another objectcontext & add just the entity I need (it then tries to add the whole graph and fails as it’s on another objectcontext). I’ve tried MergeOptions = NoTracking on my reference entities to try to get the Attach/AddObject not to navigate through these to create a graph, no avail. I've removed the navigation properties from the reference entities. I've tried AcceptAllChanges, that works but pretty useless in practice as I do still want to track & save other entities. In a simple test, I can create 2 of my proposed entities, AddObject the one I want to save and then Detach the one I dont then call SaveChanges, this works but again not great in practice. Following are a few links to some of the nifty ideas which in the end don’t help in the end but illustrate the complexity of EF for something so simple. I’m really looking for a SaveSingle/SaveAtomic method, and think it’s a pretty reasonable & basic ask for any DAL, letalone a cutting edge ORM.
Saving a single entity instead of the entire context
www.codeproject.com/KB/architecture/attachobjectgraph.aspx?fid=1534536&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=3071122&fr=1
bernhardelbl.spaces.live.com/blog/cns!DB54AE2C5D84DB78!238.entry
I'll answer this myself - sofar I've found no solution for EF1. EF4 will allow you to implement this with self-tracking entities, ie. you'll need to roll your own classes with T4 templates so there's a bit of a learning curve there (see link at end).
For now, we've decided to give our domain objects interfaces (which irks me as I really like working with poco classes in nhibernate/wcf which kills the need for this) and implement 'proposed' entites which we work with til the user decides to commit to the database, at which point we map to an EntityObject.
Some actual answers here:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/32b04a36-0579-4d6f-af48-9cb670a3d9ff

NHibernate - Usefulness

I work in a software and hardware development farm. Today one of my colleagues told me that NHibernate is only useful for small projects, and for complex or large scale projects it must be avoided. Also, it makes code harder to change.
Are those statements true?
Ebay uses Hibernate (the Java version that NHibernate is ported from). I don't consider that a small project.
As far as changing code goes, consider this: Let's assume we need to add a new property to an object.
Here is what has to be done with a hand-rolled data access layer:
Add the column to the db table.
Change every stored procedure that
deals with that object / table.
This is usually several stored
procedures in my experience.
Change the code in the mapping layer
Add the property to the Object
Here is what has to be done with NHibernate:
Add the column to the db table.
Add the property to the HBM file
Add the property to the object.
Have to agree with Daniel Augur on the first point.
On the second, "does it make code harder to change?", I'll provide a general view. Any time you use something ready-rolled you're going to run into restrictions that might not be easier to overcome. Even when the source is available, you may not wish to modify it for fear of deviating to the point of a breaking change.
Part of a software developer's job is determining whether the merits outweigh the drawbacks with 3rd party code.