I use NHibernate for the DAL of my application and in the special NHibernate SchemaExport function to delete / recreate my database schema before doing unit tests. The problem I am facing is that when I run unit tests and run SchemaExport, one of my tables cannot fall out every second time. This indicates that there is some kind of foreign key problem that prevents SchemaExport from exiting my table, but I cannot figure it out. My scheme is very simple: a people table, an address table, and a PersonAddress table to support many-to-many relationships between them.
public class Person { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual IList<Address> Addresses {get;set;} public Person() { this.Addresses = new List<Address>(); } } public class Address { public virtual int Id { get; set; } public virtual string Street1 { get; set; } public virtual string Street2 { get; set; } public virtual string Postcode { get; set; } }
and my NHibernate mapping files ...
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyHibernate" namespace="MyHibernate" > <class name="Person" table="Person.Person"> <id name="Id" column="Id"> <generator class="native" ></generator> </id> <property name="Name" column="Name" length="50"></property> <bag name="Addresses" table="[Person].[PersonAddress]" lazy="false" cascade="all"> <key column="PersonId" foreign-key="FK_Person_Person_Id"></key> <many-to-many class="Address" column="AddressId"></many-to-many> </bag> </class>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyHibernate" namespace="MyHibernate" > <class name="Address" table="Person.Address"> <id name="Id" column="Id"> <generator class="native" ></generator> </id> <property name="Street1" column="Street1" length="50"></property> <property name="Street2" column="Street2" length="50"></property> <property name="Postcode" column="Postcode" length="50"></property> </class>
and when you run `var cfg = new Configuration (); cfg.Configure (); cfg.AddAssembly (TypeOf (Person) .assembly);
new SchemaExport(cfg).Execute(false, true, false, false)
I get an SQL exception:
MyHibernate.Tests.GenerateSchemaFixture.Can_Generate_Schema: NHibernate.HibernateException: the database already has an object named "Man". ----> System.Data.SqlClient.SqlException: the database already has an object named "Person".
Any ideas?
source share