NHibernate ISession.save(newTransientEntity) 是否只会返回生成的 Id,但不会更新实体的 Id 属性?
-
03-07-2019 - |
题
使用 NHibernate.Mapping.Attributes,我有一个实体类,其中包含以下内容:
[Class]
public class EntityA
{
...
[Id][Generator(class="guid")]
public Guid Id {...}
[Property]
public string Property1 {...}
...
}
假设我使用如下代码将瞬态实体添加到持久性上下文:
...
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
...
我认为断言会成功,但实际结果是错误的。我的印象是 save 方法将使用生成的值更新实体的 Id 属性。我已经使用 NHibernate 1.2 和 2.0 进行了测试,结果相似。
所以问题是:
- 这种行为(不更新实体的 Id)是设计使然,还是我在我的机器中错误地编译了 NHibernate?
解决方案
您尚未指定 Id 的名称
代替:
[Id]
您应该指定名称:
[Id(Name="Id")]
在第一种情况下,生成的映射是错误的:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Test.EntityA, test">
<id type="Guid">
<generator class="guid" />
</id>
</class>
</hibernate-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>
请注意缺少 name="Id" 属性。
不隶属于 StackOverflow