代码之家  ›  专栏  ›  技术社区  ›  David

Fluent NHibernate:单向关联中未设置外键字段

  •  3
  • David  · 技术社区  · 14 年前

    我有一个数据库,其中有probatecases表和properties表。属性表有一个名为probatecaseid的probatecases表的外键,因此probatecases和属性之间的关系是一对多的。

    我的域层有一个probatecase类和一个属性类。probatecase类具有如下定义的属性集合:

    private IList<Property> _properties = new List<Property>();
    public virtual IEnumerable<Property> Properties { get { return _properties; } }
    public virtual Property AddProperty()
        {
          Property property = new Property();
          _properties.Add(property);
          return property;
        }
    

    Fluent NHibernate映射的相应部分如下所示:

    HasMany(x => x.Properties).Where("Deleted = 0").KeyColumn("ProbateCaseId").Cascade.All().Access.CamelCaseField(Prefix.Underscore);
    

    请注意,关联是单向的-Probatecase类有一个属性集合,但该属性类没有Probatecase成员。

    我发现查询工作正常-nhibernate正在创建适当的SQL来获取具有适当probatecaseid值的属性。

    但是,当我保存一个已添加了新属性的Probatecase时,插入SQL不包含外键字段的值-因此我收到一个SQL异常,它抱怨外键中的值为空:

    INSERT INTO AdminOverview.Properties (PropertyName) VALUES ('Name of property') -- Where the hell is the ProbateCaseId field value???
    

    我应该期望nhibernate填充外键值本身,还是应该做其他事情?

    1 回复  |  直到 9 年前
        1
  •  3
  •   Owen Pauling tmatuschek    9 年前

    http://nhibernate.info/doc/nh/en/index.html#collections-onetomany :

    非常重要的注意:如果关联的列声明为非空,则nhibernate在创建或更新关联时可能会导致约束冲突。为了避免这个问题,您必须使用与多值端(集合或包)的双向关联,标记为inverse=“true”。参见本章后面关于双向关联的讨论。