2

Is it possible with NHibernate and Sql Server to insert an entity and set one of the column values to the newly generated identity?

In pure sql I can do it by adding the default value

Create the table:

create table Test
   id int identity,
   name varchar(12),
   parentId int NOT NULL

Add a constraint:

alter table Test constraint ... default ident_current('Test') for parentId

And afterwards skip the parentId or use the DEFAULT keyword:

insert into Test values('TEST')
insert into Test values('TEST', DEFAULT)

Correct me if I'm wrong but I think that the above statements are never going to be generated by NHibernate?

For now I'm first saving my entity and then updating it with the newly created identity. This case brakes the db structure as I had to make that particular column accept NULLs.

At first I though this is going to be easy, but now, after several hours I still can't find the answer :/

Thanks in advance

MonkeyCoder
  • 2,600
  • 2
  • 28
  • 30

1 Answers1

2

You can accomplish this using the generated attribute in property mapping. For defaults set by the database, use generated="insert". For Fluent NHibernate mapping use .Generated().Insert().

EDIT:

public class Test
{
    private Test _parent;

    public Test()
    {
        _parent = this;
    }

    public Test Parent
    {
        get { return _parent == this ? null : _parent; }
        set { _parent = value ?? this; }
    }
}
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • Hi Jamie, Thank you for the info on the attribute, but I guess this means that after setting the generated="insert" I will not be able to specify my value explicitly without refreshing the entity? – MonkeyCoder Mar 23 '11 at 17:57
  • I don't know. If I understand the problem, you want to default the parent to be the same as the object but, of course, you also need to be able to set the parent. I'll edit my answer to show how I handle this scenario. – Jamie Ide Mar 23 '11 at 18:05