I am encountering foreign key error while saving child record for parent-child relationship in nhibernate. I am using Mysql as the database. Value of foreign key column inserted is "0"
Table
CREATE TABLE Company(
Id INT NOT NULL AUTO_INCREMENT,
Name Varchar(100) NOT NULL,
PRIMARY KEY (Id)
);
CREATE TABLE Client(
ClientId INT NOT NULL AUTO_INCREMENT,
CompanyId INT NOT NULL,
Name Varchar(100) NOT NULL,
PRIMARY KEY (ClientId),
FOREIGN KEY(CompanyId) REFERENCES Company(Id)
);
Class:
public class Company
{
private IList<Client> clients = new List<Client>();
public virtual IList<Client> Clients
{
get { return clients; }
set { clients = value; }
}
public virtual void AddClientToCompany(Client client)
{
client.Company = this;
clients.Add(client);
}
public virtual Company Company { get; set; }
public virtual string Name { get; set; }
public virtual int Id { get; set; }
}
public class Client
{
public virtual Company Company { get; set; }
public virtual string Name { get; set; }
public virtual int CompanyId { get; set; }
public virtual int ClientId { get; set; }
}
Company.hbm.xml
<class name="ConsoleApplication1.Company, ConsoleApplication1" table="Company">
<id name="Id" column="Id" type="int">
<generator class="native"></generator>
</id>
<property name="Name" column="Name" type="String"></property>
<bag name="Clients" table="Client" lazy="false" cascade="all" inverse="true">
<key column="CompanyId"></key>
<one-to-many class="ConsoleApplication1.Client, ConsoleApplication1" />
</bag>
</class>
Client.hbm.xml
<class name="ConsoleApplication1.Client, ConsoleApplication1" table="Client">
<id name="ClientId" column="ClientId" type="int">
<generator class="native"></generator>
</id>
<property name="Name" column="Name" type="String"></property>
<property name="CompanyId" column="CompanyId" type="int" ></property>
<many-to-one name="Company" class="ConsoleApplication1.Company, ConsoleApplication1"
column="CompanyId" cascade="none" insert="false"/>
</class>
Sql generated:
NHibernate: INSERT INTO Company (Name) VALUES (?p0);?p0 = 'Test Company' [Type: String (12)] NHibernate: SELECT LAST_INSERT_ID()
NHibernate: INSERT INTO Client (Name, CompanyId) VALUES (?p0, ?p1);?p0 = 'Test Client' [Type: String (11)], ?p1 = 0 [Type: Int32 (0)]
Runtime code:
Company company = new Company();
company.Name = "Test Company";
Client client = new Client();
client.Name = "Test Client";
company.AddClientToCompany(client);
session.Save(company);
Any ideas what could be the issue?