Search code examples
castle-activerecord

A Castle ActiveRecord relationship that does not use the Primary Key


I am connecting Castle ActiveRecord to a legacy database and I am having trouble wiring up a One-To-Many relationship. The problem is that the foreign key does not reference the primary key of the other table, it uses another column.

These are the tables (shortened for clarity):

CREATE TABLE [Rule](
    [ID] [uniqueidentifier] NOT NULL,
    [HeadingID] [int] NULL
)

CREATE TABLE [Heading](
    [ID] [uniqueidentifier] NOT NULL,
    [ID2] [int] NOT NULL
)

The HeadingID field in the Rule table is a foreign key which references the ID2 field in Heading.

So, in the definition of the Rule class I have:

[BelongsTo(Column = "HeadingID", PropertyRef = "OrderID")]
public virtual Heading Heading { get; set; }

This seems to work fine, I can access the Heading of a Rule with no problem (if I set the HasMany lazy of course).

In the Heading class definition I have:

[HasMany(Lazy = true)]
public IList<Rule> Rules { get; set; }

When I access the collection I get an SQL exception "Operand type clash: uniqueidentifier is incompatible with int." It looks like AR is attempting to do a select like this (simplified for clarity):

SELECT ... FROM Rule rules0_ ... WHERE rules0_.HeadingID = ?

Where ? is the GUID from Heading.ID (it should be the int from Heading.ID2).

I can't find a property for HasMany that allows me to set the column to which the foreign key refers. Is there any way to do this?


Solution

  • It appears that this cannot be done. The best I could do was a custom find:

    public virtual IEnumerable<Rule> Rules {
        get {
            return Rule.Queryable.Where(x => x.Heading == this);
        }
    }
    

    This works well enough for me.