7

I have a Users table where the "ID" field is a GUID field.

Using ASPNET I am creating a user account and getting the GUID back. I am trying to create associated records in my tables with that GUID as the main ID.

The problem I am running into is that when I manually set Users.ID NHibernate tries to do an Update, not an Insert. I see this with the NHibernate Profiler before it bombs out with "Unexpected row count: 0; Expected: 1".

My UsersMap for the table Users looks like:

public class UsersMap : ClassMap<Users>
{
    public UsersMap()
    {
        Id(x => x.ID, "ID"); //GUID

        Map(x => x.Name, "Name"); //string
        Map(x => x.PhoneNumber, "PhoneNumber"); //string
        Map(x => x.FaxNumber, "FaxNumber"); //string
        Map(x => x.EmailAddress, "EmailAddress"); //string

        HasMany<UsersAddressBook>(x => x.usersAddressBook).KeyColumn("ID");
    }
}

Any ideas? Thanks in advance.

3 Answers3

17

You need to specify that your id will be assigned.

Id(x => x.ID)
  .GeneratedBy.Assigned();

This will allow you to specify the value, without NHibernate trying to perform an update.

James Gregory
  • 14,173
  • 2
  • 42
  • 60
1

ISession.Save has an overload that allows you to specify identifier. Try using it, and don't set your id property manually.

maciejkow
  • 6,403
  • 1
  • 27
  • 26
0

As added value to James's answer I used:

Id(x => x.ID)
  .GeneratedBy.Assigned()
  .UnsavedValue(default_value);

Note that default_value is default value for your Id type
as in me is 0L because I use long for my Id

asakura89
  • 531
  • 1
  • 12
  • 20