I'm starting my studies now with FluentNHibernate but found great difficulty. These are my objects:
public class Region
{
public virtual Int64 Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<City> ListCity { get; set; }
public Region()
{
ListCity = new List<City>();
}
}
public class City
{
public virtual Int64 Id { get; set; }
public virtual string Name { get; set; }
}
Here is the mapping:
public class RegionMap : ClassMap<Region>
{
public RegionMap()
{
Table("tbRegion");
Id(x => x.Id)
.Column("Num_ID");
Map(x => x.Name)
.Column("Des_Name")
.Not.Nullable();
HasMany<City>(x => x.ListCity)
.Inverse()
.Cascade.SaveUpdate()
.AsBag();
}
}
public class CityMap : ClassMap<City>
{
public CityMap()
{
Table("tbCity");
Id(x => x.Id)
.Column("Num_ID");
Map(x => x.Name)
.Column("Des_City")
.Not.Nullable();
}
}
So far I think it's alright. I used to own Hibernate to generate the database A simple code to test the mapping:
List<City> lcity = new List<City>();
lcity.Add(new City()
{
Name = "Belo-Horizonte"
});
Region region = new Region()
{
ListCity = lcity,
Name = "Minas Gerais"
};
Repository.Connect(s => s.Save(region));
Look at my result
Num_ID Des_Name
1 Minas Gerais
Num_ID Des_City Region_id
1 Belo-Horizonte NULL
Why was not filled REGION_ID??
Thanks!
You have to teach it what to do with REGION_ID
- your mapping doesn't say about it.
Not sure I get the idea what is it either - but looks like it a region foreign key in City table, so most probably you need to use something like this for RegionMap
:
HasMany<City>(x => x.ListCity)
// Provide column key to reference by
.KeyColumnNames.Add("REGION_ID")
.Inverse()
.Cascade.SaveUpdate()
.AsBag();