【问题标题】:Save a Child for a existent Parent为现有的父母保存一个孩子
【发布时间】:2013-07-17 14:14:31
【问题描述】:

我有一个带有一些继承的模型,它使用 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 关联(一对一)。

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

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

谢谢。

【问题讨论】:

  • 也许您可以在ItemCommercial 中手动编写函数,女巫将返回带有您想要的数据的Item 对象。所以如果你打电话给Item i = itemCommercialObj.ConvertMyselfToItem() 你会得到想要的对象
  • 不,我不能,我必须使用我的 ORM,因为它将被其他不同的数据库使用。

标签: c# .net nhibernate inheritance hql


【解决方案1】:

你不能像这样的对象的运行时类型,因此 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 属性一样简单

【讨论】:

    【解决方案2】:

    我也是answered here

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

    所以基本上你可以做任何一个

    1. 将客户数据复制到会员中,删除客户并保存会员
    2. 使用不带子类的不同对象结构,其中 Member 是具有自己的 ID 和对客户的引用的不同表
    3. 使用原生 sql 将行插入到 Member...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2015-03-26
      相关资源
      最近更新 更多