I'm modeling accounting where I have accounts with transactions that debit one account and credit another.
Here are the details of the situation (simplified). My tables (in SQL Server 2008) are:
CREATE TABLE Account
(
AccountID int IDENTITY(1,1) NOT NULL,
AccountNumber nvarchar(10) NOT NULL
)
CREATE TABLE [Transaction]
(
TransactionID [bigint] IDENTITY(1,1) NOT NULL,
DebitAccountID [int] NOT NULL,
CreditAccountID [int] NOT NULL,
Amount money NOT NULL
)
My classes are:
public class Account
{
public int Id { get; set; }
public string AccountNumber { get; set; }
public IList<Transaction> Transactions { get; set; }
}
public class Transaction
{
public int Id { get; set; }
public Account DebitAccount { get; set; }
public Account CreditAccount { get; set; }
}
So the question is "How do I map the Transactions collection in the Account class using fluent NHibernate?"
What I want (for performance reasons) is for the accessing of the transactions collection to execute the query:
SELECT ...
FROM [Transaction]
WHERE DebitAccountID=@accountID OR CreditAccountID=@accountID
The important part there is the OR in the where clause.
So the code I need is:
public class AccountMap : SubclassMap<Account>
{
public AccountMap()
{
Id(x => x.Id).Column("AccountID");
Map(x => x.AccountNumber);
HasMany(x => x.Transactions)
// What goes here to explain this mapping to NHibernate?
.Inverse().Cascade.AllDeleteOrphan()
.Access.CamelCaseField();
}
}
Note: I am aware that I could map the transactions as two separate collections, one for "debits" and the other for "credits". That is not an acceptable answer because of performance issues. In particular, there is actually a second type like this related to the account (resulting in even more queries) and mapping as two collections prevents the use of eager loading with Fetch()
. The second type is PaymentScheduleLine
which contains a plan of all the correct payment transactions over the life of the account. It is associated to the account in the same way as transaction i.e. PaymentScheduleLine
has a DebitAccount
and CreditAccount
and Account
has a PaymentSchedule
collection. Typically, complex calculations involve the relationship between the transactions and the payment schedule.