简体   繁体   中英

One to Many Mapping in Fluent NHibernate with Composite Ids

I'm having problems with one to many mapping with composite key on both sides.

Here is what I have so far:

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();
    }
}

Here is database structure:

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;

I know it is not correct and I'm now out of ideas what is wrong as I have started learning NHibernate like few hours ago. Can somebody point me out what is wrong in my code ?

the reference to oneSide must be the keyreference because you can not map the columns twice.

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();
    }
}

Accessing column B from ManySide is as simple as manysideObj.OneSide.B and as long as you only access One side properties forming the primary key it it doesn't even have to load OneSide.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM