NHibenate: Is there a way to create a one to many bidirectional relationship with composite keys?

190 views
Skip to first unread message

freshrebel

unread,
Jul 15, 2019, 12:15:59 PM7/15/19
to nhusers
I'm trying to setup a bidirectional relationship in NHibernate on 2 classes both with composite keys that overlap.
Another difficulty is that I can't just edit the SQL tables to for example add a proper ID.

This is probably an easy question but i can't find the answer anywhere.

I've got the HasMany down, as far as i can see. But I'm stuck with the HasOne. Also tried with Reference.

public class Parent
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public List<Child> Children { get; set; }
    public string Data { get; set; }
}
public class Child
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public Parent Parent { get; set; }
    public string Data { get; set; }
}

public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        CompositeId()
            .KeyProperty(x => x.A)
            .KeyProperty(x => x.B)
            .KeyProperty(x => x.C);
        Map(x => x.Data);
        HasMany(x => x.Children)
                .KeyColumn("A")
                .KeyColumn("B")
                .KeyColumn("C");
    }
}
public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        CompositeId()
            .KeyProperty(x => x.A)
            .KeyProperty(x => x.B)
            .KeyProperty(x => x.C)
            .KeyProperty(x => x.D);
        Map(x => x.Data);
        HasOne(x => x.Parent);
        // also tried
        //References<Parent>(x => x.Parent)
                //.Columns("A", "B", "C");
    }
}

The error i get now is: 
NHibernate.FKUnmatchingColumnsException: 'Foreign key (FK_3346D8AD:Child [C])) must have same number of columns as the referenced primary key (Parent [A, B, C])'

freshrebel

unread,
Jul 18, 2019, 6:41:27 AM7/18/19
to nhusers
This error has been resolved with this code:

Though now I'm having a new error:

An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.


With this inner exception: Unable to build the insert statement for class Parent: a failure occured when adding the Id of the class


This inner exception has another inner exception: The column 'A' has already been added in this SQL builder Parameternaam: columnName


How can I manage this without changing the column name in the database?


Op maandag 15 juli 2019 18:15:59 UTC+2 schreef freshrebel:
Reply all
Reply to author
Forward
0 new messages