【问题标题】:fluent nhibernate mapping with not null foreign key (HasMany)具有非空外键的流畅 nhibernate 映射 (HasMany)
【发布时间】:2012-09-05 07:08:43
【问题描述】:

我在 nhibernate 中有以下映射。 当我调用 Session.Merge(myparent) 时,我在插入时收到一条错误消息,指出无法将 NULL 插入到外键 (ParentItemId) 列中。

如何调整映射以便在插入时插入父键。如果我使外键可以为空,则此映射有效,但会向数据库发出两个单独的语句。

这种关系是一对多的,没有对子类的父级的引用。

  • 子类没有父属性。
  • 孩子依赖于父母。
    HasMany(map => map.Children).Table("ChilrenTable")
       .KeyColumn("ParentItemId") // this is not nullable.
       .Cascade
       .AllDeleteOrphan();
    

    示例更新

    // entity here is the parent instance, which contains the list
    // of children.
    using (var tx = Session.BeginTransaction())
    {
        entity = Session.Merge(entity); // this line causes the problem.
        Session.SaveOrUpdate(entity);
        Session.Flush();
        tx.Commit();
        return entity;
    }
    
  • 【问题讨论】:

      标签: c# nhibernate fluent-nhibernate


      【解决方案1】:

      Inverse Attribute in NHibernate

      HasMany(map => map.Children).Table("ChilrenTable")
         .KeyColumn("ParentId") // this is not nullable.
         .Inverse()  // <--- This is the key here
         .Cascade
         .AllDeleteOrphan();
      

      【讨论】:

      • 我试过这个,但合并仍然失败。也许它与合并有关。我正在将发送到 WCF 服务的已发布 Web 数据的更改合并回数据库。 WCF 服务正在合并和更新数据。它仍然尝试插入一个空值,然后更新外键值。
      • 进一步阅读,似乎逆向仅适用于双向关系。就我而言,这种关系不是双向的。父项拥有子项,但子项没有父属性,因此没有到父项的休眠映射。
      • @Jim 也许你应该让它成为一个双向关系。
      • 嗨,科尔,我也开始这么想。我没有的原因是 WCF 上的序列化可能是循环关系的问题。我想我会使用双向关系并将所有数据合约标记为 IsReference = true。
      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 2023-03-14
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      相关资源
      最近更新 更多