插入过程中流畅的Nhibernate失败

时间:2010-12-26 13:44:22

标签: nhibernate fluent-nhibernate

我使用Fluent Nhibernate时遇到问题,我有以下型号。当我尝试使用新的Geography保存酒店时,我得到了外键异常,看起来像Nhibenate无法以正确的顺序保存数据,是否可以通过Fluent Nhibernate来纠正?

public class Geography {
  public virtual int CityID { get; set; }
  public virtual string CountryCode { get; set; }
}

public class Hotel
{
        public virtual int HotelID { get; set; }
        public virtual Geography City { get; set; }

}

映射

 public class HotelMap : ClassMap<Hotel>
 {
  public HotelMap()
  {
   Id(x => x.HotelID)
                .GeneratedBy
                .Identity();             
            References(x => x.City, "CityId")
                .Cascade.All();                                               
  }

 }

 public class GeographyMap : ClassMap<Geography>
 {
  public GeographyMap()
  {
   Id(x => x.CityID);
   Map(x => x.CountryCode);
            HasMany(a => a.Hotels)
                .Cascade.All();
  }
 }

添加了生成的映射

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="Hotel" table="`Hotel`">
    <id name="HotelID" type="System.Int32">
      <column name="HotelID" />
      <generator class="assigned" />
    </id>
    <many-to-one cascade="all" class="Geography" foreign-key="HotelGeography" name="City">
      <column name="CityId" />
    </many-to-one>
  </class>
</hibernate-mapping>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="Geography" table="`Geography`">
    <id name="CityID" type="System.Int32">
      <column name="CityID" />
      <generator class="assigned" />
    </id>
    <bag cascade="all" inverse="true" name="Hotels" mutable="true">
      <key>
        <column name="HotelID" />
      </key>
      <one-to-many class="Hotel" />
    </bag>
    <property name="CountryCode" type="System.String">
      <column name="CountryCode" />
    </property>
  </class>
</hibernate-mapping>

2 个答案:

答案 0 :(得分:1)

尝试为Geography类指定标识生成器。如果您希望拥有数据库生成的唯一标识符(如身份),则可以通过将.GeneratedBy.Native()添加到Id(...)类中的GeographyMap来实现此目的。

答案 1 :(得分:1)