1

我有一个带有一些继承的模型,它使用 nhibernate 来持久化数据库。使用流利的 nhibernate 的 nhibernate 映射工作正常,但我有一个场景,我需要为现有的父母保存一个孩子。我的模型如下所示:

public class Item
{
   public long Id { get; set; }
   public string Name { get; set; }
   // other properties
}

public class ItemCommercial : Item
{
   public decimal Value { get; set; }
   // other properties
} 

在我的数据库中,各个表是按Id <-> Id(一个一个)相关的。

我想知道,如何只保存数据库中ItemCommercial存在的实例。Item我有项目的 ID,但我不知道如何说 nhibernate 只说孩子,而是创建一个新项目,例如:

session.Save(itemCommercialObj); // will create a Item and ItemCommercial with the same Id

谢谢你。

4

2 回答 2

0

正如我在这里也回答了

不,不可能将已经持久化的对象“升级”到它的子类。Nhibernate 根本不支持这一点。如果您使用与基类相同的 ID 来保护子类,Nhibernate 只需使用对象的新 ID 创建一个副本,而不是创建对 Member 的引用...

所以基本上你可以做

  1. 将客户的数据复制到会员中,删除客户并保存会员
  2. 使用不带子类的不同对象结构,其中 Member 是具有自己的 ID 和对 Customer 的引用的不同表
  3. 使用本机 sql 将行插入到 Member...
于 2013-10-15T20:34:25.443 回答
0

你不能像这样的对象的运行时类型,因此 NH 不支持它。将设计更改为

public class Item
{
    public long Id { get; set; }
    public string Name { get; set; }
    public CommercialValue CommercialValue { get; set; }
    // other properties
}

public class CommercialValue
{
    public Item Item { get; set; }
    public decimal Value { get; set; }
    // other properties
}

和一对一的映射。然后就像设置 CommercialValue 属性一样简单

于 2013-07-24T14:37:55.850 回答