Manually setting the ID
Asked Answered
N

3

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.

Nemertean answered 3/6, 2010 at 22:5 Comment(0)
I
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.

Irrelative answered 3/6, 2010 at 22:33 Comment(1)
This appears to be the best method. It also works perfectly. Thanks for your help.Nemertean
Z
1

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

Zoon answered 3/6, 2010 at 22:9 Comment(0)
R
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

Ribera answered 2/7, 2012 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.