Search code examples
c#fluent-nhibernateforeign-keysmappingfluent-nhibernate-mapping

Fluent NHibernate HasMany mapping inserts null in foreign key


I have 2 entities:

public class Parent
{
    public virtual string Number { get; set; }
    public virtual IList<Child> Children { get; set; }
    public Parent()
    {
        Phones = new List<Child>();
    }
}
public class Child
{
    public virtual string Number { get; set; }
    public virtual Parent Parent { get; set; }
}

and mappings:
child

 public ChildMap()
        {
            Map(x => x.Number).Not.Nullable();
            References(x => x.Parent).Nullable().LazyLoad().Cascade.None();
        }

and parent

public ParentMap()
    {
        Map(x => x.Number).Not.Nullable();
        HasMany(x => x.Children).Inverse().Cascade.All();
    }

but when i insert children to parent, it goes with null in parent foreign key.

var p = rep.Get(g => g.Id == 1);
Enumerable.Range(0, 100).Select(s => new Child()
    {
        Number = s.ToString()
    }).ToList().ForEach(p.Children.Add);
rep.Update(p);
rep.Flush();

actualy everything like in post NHibernate fluent HasMany mapping inserts NULL Foreign key
But insert link like this test.Orders.Add(new Order("test") { Company = test }); absolutly not true way, so i need help, any ideas?


Solution

  • The answer is

    public ParentMap()
        {
            Map(x => x.Number).Not.Nullable();
            HasMany(x => x.Children).Cascade.All();
        }
    

    Without inverse