I love NHibernate and I love Fluent NHibernate. Fluent NHibernate allows you to use NHibernate without the XML configuration files that would normally be required by NHibernate. In fact, by using the AutoMap feature of Fluent NHibernate, you can use NHibernate without writing ANY additional lines of code beyond adding virtual to your POCO classes. That sounds great.
Sometimes, however, NHibernate can give you error messages that aren't as intuitive as they could be. This is a small complaint because we software developers can always figure out how to do things....right? So you have created your classes, set up Fluent NHibernate and tried to save something only to find that NHibernate is not saving your entity. You try and try, but NHibernate will not save your entity. You look at the error message and you see the following:
Unexpected row count: 0; expected: 1
That message doesn't look good. Why won't NHibernate save? Whatever could the NHibernate problem be? Well I don't know all of the reasons that this error message might occur, but I do know one reason that I'm going to tell you about.
If you are using GUIDs or INTs as the primary key on your entity, NHibernate needs to see that entity id as empty so that it will know that the item you are saving is new. You will get the error shown above if you try to add the GUID or INT yourself. I know. I know. This is kind of counter to how you do things in Entity Framework, but isn't NHibernate smart? It can and will generate the id for you so you can sit back and relax (well you can't really relax, but NHibernate will create the id for you). To solve the problem, do not try to assign an int or Guid to your id. When NHibernate sees that the value is empty, NHibernate will recognize this to be a new item and perform a database Insert instead of an Update.
Wasn't that simple. I just told you to do nothing and I solved your problem.
Hope this saves you some time!
Smooches,
Kila
Problem:
This blog is for all Microsoft & .net lovers who may find themselves in need of help or information once in a while. We all have questions and we all need to know more than we know right now. When I come across things that I think may be useful, I post it. When I have something to say that I think is important, which is everything, I post it. All of my C#, ASP.NET, VB, AJAX & programming friends around the world are welcome to the info in my blog - Ramblings Of A Crazy DotNet Woman!
Subscribe to:
Post Comments (Atom)
1 comment:
Thanks it Helped, i have one composed key with 3 id's. i've missed one.
Post a Comment