2

I have a parent and child table and entites are created and mapped using one to many relation ship. On one to many side when i use Inverse() then the child table's foreign key value is inserted as null.

public class TableA
{
   public virtual long ID { get; set; }
   public virtual string Name { get; set; }
   public virtual IList<TableB> TableB { get; set; }
}

public class TableB
{
   public virtual long ID { get; set; }
   public virtual string Name { get; set; }
   public virtual TableA TableA { get; set; }
}

public class TableAMap : ClassMap<TableA>
{
   public TableAMap()
   {
      Id(x=>x.ID);
      Map(x=>x.Name).Column("Name");
      HasMany(x=>x.TableB)
          .KeyColumn("TableA_ID")
          .Inverse()
          .Cascase.All()
          .Not.LazyLoad();
   }
}

public class TableBMap : ClassMap<TableB>
{
   public TableBMap()
   {
      Id(x=>x.ID);
      Map(x=>x.Name).Column("Name");
      References(x=>x.TableA).Column("TableA_ID").Not.LazyLoad();
   }
}

Note When the Inverse() is removed from many to one the new records are inserted without any issues and the foreign key is inserted without any issues but when i update a record the foreign key of the existing records are replaced as null.

Please help me i looked in to similar questions but it doesn't help me.

Fluent NHibernate one-to-many relationship setting foreign key to null

Community
  • 1
  • 1
Desmond
  • 1,308
  • 1
  • 19
  • 27
  • You should post your real mapping. Your `HasMany(x=>x.TableB).KeyColumn("TableA_ID").Inverse().Cascase.All().Not.LazyLoad();` doesn't seem to work with `` – Origin Nov 27 '12 at 04:37
  • Yes sorry i have corrected the one with `HasMany(x=>x.TableB).KeyColumn("TableA_ID").Inverse().Cascase.All().Not‌​.LazyLoad();` – Desmond Nov 27 '12 at 06:59
  • This example is hard to decipher. Again, I think you should post the actual code (or a subset of it) and also the schema you're currently working with. – Origin Nov 27 '12 at 15:53

2 Answers2

3

Refer to this link which has the solution for this issue.

Refer this Solution link

The map class should be:

public class TableAMap : ClassMap<TableA>
{
   public TableAMap()
   {
      Id(x=>x.ID);
      Map(x=>x.Name).Column("Name");
      HasMany<TableB>(x=>x.TableB)
          .KeyColumn("TableA_ID")
          .Cascade.All().Inverse();
   }
}

public class TableBMap : ClassMap<TableB>
{
   public TableBMap()
   {
      Id(x=>x.ID);
      Map(x=>x.Name).Column("Name");
      References<TableA>(x=>x.TableA).Column("TableA_ID").Not.Nullable();
   }
}
Djensen
  • 1,337
  • 1
  • 22
  • 32
Desmond
  • 1,308
  • 1
  • 19
  • 27
1

it's hard to tell exactly without seeing the code which inserts. However my crystal ball tells me you probably forgot the last line

Parent parent = new Parent();
Child child = new Child();
parent.Children.Add(child);
child.Parent = parent;     <-- this is important because this will maintain the foreign key
Firo
  • 30,626
  • 4
  • 55
  • 94