Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate - HasMany on composite key

How do you create a HasMany relation on a legacy database which has no Foreign Key and columns differently named? I know how to create a one-to-one relation on HeaderVersion using References, but don't know how to create HasMany from Header 1 to * HeaderVersion. Join condition should be:

Header.Id1 = HeaderVersion.PId1 AND Header.Id2 = HeaderVersion.PId2

Model

Domain:

public class Header {
    public virtual int Id1 { get; set; }
    public virtual int Id2 { get; set; }
    public virtual string Something { get; set; }
}

public class HeaderVersion {
    public virtual int PId1 { get; set; }
    public virtual int PId2 { get; set; }
    public virtual int Version { get; set; }
    public virtual string SomethingFoo { get; set; }
}

Map:

 public HeaderMap() {
        Table("Header");
        LazyLoad();
        CompositeId().KeyProperty(x => x.Id1, "Id1")
                     .KeyProperty(x => x.Id2, "Id2");
        Map(x => x.Something).Column("Something");
 }

 public HeaderVersionMap() {
        Table("HeaderVersion");
        LazyLoad();
        CompositeId().KeyProperty(x => x.PId1, "PId1")
                     .KeyProperty(x => x.PId2, "PId2")
                     .KeyProperty(x => x.Version, "Version");
        Map(x => x.SomethingFoo).Column("SomethingFoo");
 }
like image 434
redman Avatar asked Oct 16 '13 09:10

redman


1 Answers

Assuming Header is (omitted overrides for GetHashCode and Equals)

public class Header
{
    public virtual int Id1 { get; set; }
    public virtual int Id2 { get; set; }
    public virtual string Something { get; set; }
    public virtual ICollection<HeaderVersion> Versions { get; set; }
}

HeaderMap should look like :

public class HeaderMap : ClassMap<Header>
{
    public HeaderMap()
    {
        Table("Header");
        LazyLoad();
        CompositeId().KeyProperty(x => x.Id1, "Id1")
                     .KeyProperty(x => x.Id2, "Id2");
        Map(x => x.Something).Column("Something");
        HasMany(x => x.Versions).AsBag().KeyColumns.Add("PId1", "PId2");
        // Fetch, Inverse, Cascade depend on your mapping strategy
    }
}
like image 137
jbl Avatar answered Sep 21 '22 07:09

jbl