Is it true that NHibernate ISession.save(newTransientEntity) will only return generated Id, but NOT updating the Id property of the entity?

安稳与你 提交于 2019-12-24 01:55:09

问题


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?

回答1:


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.



来源:https://stackoverflow.com/questions/411127/is-it-true-that-nhibernate-isession-savenewtransiententity-will-only-return-ge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!