问题
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