FluentNhibernate Cartographic Dictionaries Foreign Key Remains Null

I have a simple Fluent-NHibernate mapping that gives me a headache! I am trying to display a dictionary for one of the objects, but its FK remains zero.

Here is the entity code:

public class Person { public Person() { PhoneNumbers = new Dictionary<string, Phone>(); } public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual IDictionary<string, Phone> PhoneNumbers { get; set; } } public class Phone { public virtual int Id { get; set; } public virtual string Type { get; set; } public virtual string Number { get; set; } } 

Now, here is the mapping:

 public class PersonClassMap : ClassMap<Person> { public PersonClassMap() { Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Name); HasMany(x => x.PhoneNumbers).AsMap(y => y.Type).Cascade.All(); } } public class PhoneClassMap : ClassMap<Phone> { public PhoneClassMap() { Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Type); Map(x => x.Number); } } 

Last, here is the Test I am doing:

  static void Main(string[] args) { ConfigureSessionFactory(); using (var session = _sessionFactory.OpenSession()) { var john = new Person(); john.Name = "John"; Phone home = new Phone { Type = "Home", Number = "12345" }; john.PhoneNumbers.Add(home.Type, home); session.Save(john); } } 

For some reason, when I look in the database, the Person_id phone Person_id remains empty, and when I load a person from the database, the PhoneNumbers dictionary remains empty.

Why? And how to solve this problem? What am I drawing wrong?

+4
source share
1 answer

This problem was finally resolved by adding transactions. I don't know why this works (which makes me pretty sad, actually), but it does.

 using (var session = _sessionFactory.OpenSession()) { var transaction = session.BeginTransaction(); john.Name = "John"; Phone home = new Phone { Type = "Home", Number = "12345" }; john.PhoneNumbers.Add(home.Type, home); session.Save(john); transaction.Commit(); } 

Hope this helps too, as it took me too long to get it right.

0
source

All Articles