1

我在使用双方的复合键进行一对多映射时遇到问题。

这是我到目前为止所拥有的:

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。有人可以指出我的代码有什么问题吗?

4

1 回答 1

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。

于 2012-09-14T07:06:25.487 回答