Search code examples
nhibernatefluent-nhibernatefluent-nhibernate-mapping

Specifying the name of a foreign key column


public class TransactionIdentityModelMapping : ClassMap<TransactionIdentityModel>
{
    public TransactionIdentityModelMapping()
    {
        Table("TransactionIdentities");
        Id(x => x.Id);
        References(x => x.Transaction);
    }
}

public class TransactionModelMapping : ClassMap<TransactionModel>
{
    public TransactionModelMapping()
    {
        Table("Transactions");
        Id(x => x.Id);
        HasMany(x => x.Identities);
    }
}

TransactionIdentityModel.Transaction is of type TransactionModel. This means there is a column created called "TransactionModel_id". How can I change this column name?

I have tried:

References(x => x.Transaction).Column("Transaction_id");

And:

References(x => x.Transaction).ForeignKey("Transaction_id");

And:

References(x => x.Transaction).Column("Transaction_id").ForeignKey("Id").Fetch.Join();

These all yield 2 columns, the one I want ("Transaction_id") and the original ("TransactionModel_id").

Do I need to also do something with the HasMany?

Edit the models:

public class TransactionModel
{
    /// <summary>
    /// For NHibernate
    /// </summary>
    protected TransactionModel()
    {
    }

    public static TransactionModel FromId(TransactionIdentityModel tranIdentity)
    {      
        return new TransactionModel
            {
                Identities = new List<TransactionIdentityModel> { tranIdentity }
            };
    }

    public virtual Guid Id { get; protected set; }

    public virtual IList<TransactionIdentityModel> Identities { get; protected set; }
}

public class TransactionIdentityModel
{        
    public virtual Guid Id { get; protected set; }

    public virtual TransactionModel TransactionModel { get; set; }
}

Yielding 2 columns, this is the SQL being generated if I use the map: References(x => x.Transaction).Column("Transaction_id").ForeignKey("Id").Fetch.Join();

alter table TransactionIdentities 
    add constraint Id 
    foreign key (Transaction_id) 
    references Transactions

alter table TransactionIdentities 
    add constraint FK958B77026F5C4B80 
    foreign key (TransactionModel_id) 
    references Transactions

Solution

  • Assuming Transaction_Id is the foreign key to the related TransactionModel then you need to change your References statement to this:

     References(x => x.Transaction).Column("Transaction_id");
    

    This will override nHibernates default expectation for the field to be TransactionModel_id

    Looking at this question Prevent Nhibernate schemaexport from generating foreign key constraints on has many relationship, I think you will have to change your HasMany mapping to this:

     HasMany(x => x.Identities).KeyColumn("Transaction_id")