views:

1441

answers:

1

Using NHibernate.Mapping.Attributes, I have a entity class with something like:

[Class]    
public class EntityA
{
  ...
  [Id][Generator(class="guid")]
  public Guid Id {...}

  [Property]
  public string Property1 {...}
  ...
}

Let say if I add a transient entity to the persistence context with code like this:

...
Guid id;
using(ISession s = sessionFactory.OpenSession())
using(ITransaction t = s.BeginTransaction())
{
  EntityA entity = new EntityA();
  entity.Property1 = "Some Value";
  id = (Guid) s.Save(entity);
  t.Commit();
  Assert.IsTrue(s.Contains(entity)); // <-- result: true
}


Assert.AreEquals(id, entity.Id); // <-- Result: false, Expexted: true
...

I suppose that the assert will be success, but the actual result is false. I have the impression that the save method will update the Id property of the entity with the generated value. I have tested this by using both NHibernate 1.2 and 2.0 with similar result.

So the question is:

  • Is this behaviour (not updating the entity's Id) by design, or I have wrong compilation of NHibernate in my machine?
+3  A: 

You haven't specified the name of the Id

Instead of:

[Id]

you should specify the name:

[Id(Name="Id")]

In the first case the generated mapping is wrong:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Test.EntityA, test">
    <id type="Guid">
      <generator class="guid" />
    </id>
  </class>
</hibernate-mapping>

while in the second case you will get the correct mapping:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Test.EntityA, test">
    <id type="Guid" name="Id">
      <generator class="guid" />
    </id>
  </class>
</hibernate-mapping>

Notice the name="Id" attribute which was missing.

Darin Dimitrov
Thanks, it works! I was relying too much for the serializer to deduce the the Id name based on the property that IdAttribute is applied to. Thanks again.
Nordin