Nhibernate: mapping two different properties between the same 2 entities
- by Carlos Decas
I have a Class A:
public class ClassA
{
public int ID {get; private set;}
public string Code {get; private set;}
public ClassB B {get; private set;}
public IList<ClassB> ListB {get; private set;}
}
And a ClassB:
public class ClassB
{
public int ID {get; private set;}
public string Code {get; private set;}
public ClassA A {get; private set;}
//some other attributes...
}
And the Mappings:
public ClassAMap()
{
Table("ClassA");
Id(classA => classA .ID, "ID").GeneratedBy.Identity();
Map(classA => classA.Code, "Code").Unique().Not.Nullable();
//HERE IS THE PROBLEM: --------
References(classA => classA.B,"IDClassB").Cascade.SaveUpdate();
//-----
HasMany(classA => classA.ListB).Table("ClassB").KeyColumn("IDClassA").AsBag().Not.LazyLoad().Inverse().Cascade.AllDeleteOrphan();
}
ClassB Mappings:
public ClassBMap()
{
Table("ClassB");
Id(classB => classB.ID).GeneratedBy.Identity();
References(classB => classB.A, "IDClassA").ForeignKey("ID").Cascade.SaveUpdate();
}
The mappings for ListB in classA worked ok, because at first the was only ListB property and not B, when i had to map B i tried this:
References(classA => classA.B,"IDClassB");
The mapping test failed because B wasn't saved, so i did this:
References(classA => classA.B,"IDClassB").Cascade.SaveUpdate();
This time B was saved, but by saving B, classA was inserted two times, by A.B and by B.A.
How can i solve this problem? Why does it work for the ListB property and not for the B property? Thanks