将只返回生成的ID

将只返回生成的ID

本文介绍了这是真的,NHibernate的ISession.save(newTransientEntity)将只返回生成的ID,但不更新实体的Id属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NHibernate.Mapping.Attributes,我有一个实体类的东西,如:

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 {...}
  ...
}

让说,如果我添加了一个临时实体与code这样的持久化上下文:

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
...

我想,断言将是成功的,但实际结果是假的。我有IM pression的保存方法将生成的值更新实体的ID属性。我曾经同时使用NHibernate的1.2和2.0类似的结果测试这一点。

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.

所以,问题是:


  • 这种行为是由设计(不更新实体的ID),或者我有NHibernate的错编译在我的机器?

推荐答案

您还没有指定的ID的名称

You haven't specified the name of the Id

而不是:

[Id]

您应该指定名称:

[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>

请注意这是缺少NAME =id属性。

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

这篇关于这是真的,NHibernate的ISession.save(newTransientEntity)将只返回生成的ID,但不更新实体的Id属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:58