我遇到了双向复合键的一对多映射问题。
这是我到目前为止所做的:
public class OneSide
{
public virtual int A { get; set; }//-A,B,C,D together form primary key
public virtual int B { get; set; }
public virtual int C { get; set; }
public virtual int D { get; set; }
public virtual int OtherData { get; set; }
public virtual IList<ManySide> Ls { get; set; }
}
public class OneSideMap : ClassMap<OneSide>
{
public OneSideMap()
{
LazyLoad();
CompositeId().KeyProperty(x => x.A).KeyProperty(x => x.B).KeyProperty(x => x.C).KeyProperty(x => x.D);
Map(x => x.OtherData).Not.Nullable();
HasMany(x => x.Ls).KeyColumns.Add("A", "B", "C", "D").Inverse().Cascade.All();
}
}
public class ManySide
{
public virtual OneSide OneSide { get; set; }
public virtual int A { get; set; }//-A,B,C,D,E together form primary key
public virtual int B { get; set; }
public virtual int C { get; set; }
public virtual int D { get; set; }
public virtual int E { get; set; }
public virtual int OtherData2 { get; set; }
}
public class ManySideMap : ClassMap<ManySide>
{
public ManySideMap()
{
LazyLoad();
CompositeId().KeyReference(x => x.A).KeyReference(x => x.B).KeyReference(x => x.C).KeyReference(x => x.D).KeyProperty(x => x.E);
Map(x => x.OtherData2).Not.Nullable();
References(x => x.OneSide).Columns("A", "B", "C", "D").Cascade.All();
}
}
这是数据库结构:
table: OneSide:
int A;
int B;
int C;
int D;
int OtherData;
table: ManySide:
int A;
int B;
int C;
int D;
int E;
int OtherData2;
我知道这是不正确的,因为我几小时前开始学习NHibernate,所以我现在已经没想到出了什么问题。有人能指出我的代码中有什么问题吗?
答案 0 :(得分:0)
对oneSide的引用必须是keyreference,因为您无法将列映射两次。
public class ManySideMap : ClassMap<ManySide>
{
public ManySideMap()
{
LazyLoad();
CompositeId()
.KeyReference(x => x.OneSide, "A", "B", "C", "D")
.KeyProperty(x => x.E);
Map(x => x.OtherData2).Not.Nullable();
}
}
从ManySide访问B列就像manysideObj.OneSide.B
一样简单,只要您只访问形成主键的一侧属性,它甚至不必加载OneSide。