NHibernate映射没有向外键引用添加ON DELETE CASCADE选项

时间:2010-12-17 07:37:02

标签: nhibernate nhibernate-mapping

这是我的NHibernate映射。

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="HelloNHibernate" namespace="HelloNHibernate">
  <class name="Showing" table="showing">
    <id name="Id" column="showing_id">
      <generator class="identity"/>
    </id>
    <many-to-one class="Theater" name="Theater" column="theater_id" foreign-key="fk_showing_theater_theater_id" cascade="delete" lazy="false" fetch="join"/>
    <many-to-one class="Movie" name="Movie" column="movie_id" foreign-key="fk_showing_movie_movie_id" cascade="delete" lazy="false" fetch="join" />
  </class>
</hibernate-mapping>

这是SchemaExport工具生成的SQL(PostgreSQL):

CREATE TABLE showing
(
  showing_id serial NOT NULL,
  theater_id integer,
  movie_id integer,
  CONSTRAINT showing_pkey PRIMARY KEY (showing_id),
  CONSTRAINT fk_showing_movie_movie_id FOREIGN KEY (movie_id)
      REFERENCES movie (movie_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_showing_theater_theater_id FOREIGN KEY (theater_id)
      REFERENCES theater (theater_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

我做错了什么?谢谢!

3 个答案:

答案 0 :(得分:8)

NHibernate只能对反向集合生成on delete cascade个约束。

您的域名示例:

<class name="Movie">
  ...
  <bag name="Showings" inverse="true" cascade="all">
    <key column="Foo" on-delete="cascade" /><!--Here's the magic-->
    <one-to-many class="Showing" />
  </bag>
</class>

答案 1 :(得分:5)

为了补充已接受的答案,以下是使用Fluent NHibernate的方法:

public class MovieMap : ClassMap<Movie>
{
     public MovieMap()
     {
         ...
         HasMany(c => c.Showings)
              .Inverse()
              .KeyColumn("Foo")
              .Cascade.All()
              .ForeignKeyCascadeOnDelete() // here's the magic
              .ForeignKeyConstraintName("FK_Movie_Showing"); // this is optional - name is autogenerated otherwise

答案 2 :(得分:1)

NHibernate的级联设置不会生成级联外键。它控制NHIBnerate在刷新会话时将采取的操作。

此外,关系的许多方面将删除级联到一方是非常不寻常的。删除“显示”时,您的映射将删除相关的电影和剧院。