Hi nhusers,
Just started to play around with nhibernate 2.1.2. Having some trouble
implementing a one-to-many relationship though. Here is what i do:
1. I have got two tables with a foreign key constraint:
Municipality (ID, Name)
City (ID, MunicipalityID, Name)
2. I have defined my corresponding objects like this:
public class CityPoco
{
public virtual long ID { get; set; }
public virtual string Name { get; set; }
public virtual MunicipalityPoco Municipality { get; set; }
}
and
public class MunicipalityPoco
{
public virtual long ID { get; set; }
public virtual string Name { get; set; }
public virtual IList<CityPoco> Cities { get; set; }
}
3. Then i have defined my mapping like this:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Sample.Common.Kernel.CityPoco, Common"
table="[Kernel.City]">
<id name="ID">
<generator class="identity"/>
</id>
<property name="Name" type="String"/>
<many-to-one name="Municipality" column="MunicipalityID"
class="Sample.Common.Kernel.MunicipalityPoco, Common" />
</class>
</hibernate-mapping>
and
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Sample.Common.Kernel.MunicipalityPoco, Common"
table="[Kernel.Municipality]">
<id name="ID">
<generator class="identity"/>
</id>
<property name="Name" type="String"/>
<bag name="Cities" table="[Kernel.City]" cascade="all"
inverse="true">
<key column="MunicipalityID" not-null="true"></key>
<one-to-many class="Sample.Common.Kernel.CityPoco,
Common"></one-to-many>
</bag>
</class>
</hibernate-mapping>
4. Finally, i would like to add a new city to an existing municipality
like this:
ISession session = SessionFactory.GetSession();
MunicipalityPoco mun =
session.Load<MunicipalityPoco>((long)2);
CityPoco city = new CityPoco();
city.Name = "New city";
mun.Cities.Add(city);
session.SaveOrUpdate(mun);
session.Flush();
In the last line (when the actualy SQL Query is executed), it throws
an error complaining that i cannot insert NULL into "MunicipalityID"
in the "City" table. Now i wonder: why doesn't it set the
MunicipalityID to the actual ID of the Municipality instead of trying
to insert NULL?
Help is very much appreciated :-)
Thanks in advance.
Kasper
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/nhusers?hl=en.