How do I create a Fluent nHibernate component mapping with data from another table
I'm running into some difficulty setting up a Fluent nHibernate mapping where I'm trying to use the Component function to build up an object that with data from two related database tables.
Below is a simplified version of the database and code that outlines the basic problem I'm having.
I've got a database setup that looks similar to the following:
Account
- AccountId INT (PRIMARY KEY)
- Currency VARCHAR(3)
SubAccount
- SubAccountId INT (PRIMARY KEY)
- AccountId INT (FOREIGN KEY reference to Account)
- Balance DECIMAL
I'm trying to map this data into the following classes:
public class Account
{
public virtual int Id { get; private set; }
public virtual string Currency { get; private set; }
}
public class SubAccount
{
public virtual int Id { get; private set; }
public virtual Account Account { get; private set; }
public virtual Money Balance { get; private set; }
}
The Money
class looks like:
开发者_开发问答public class Money
{
public decimal Value { get; private set; }
public string Currency { get; private set; }
}
The part I'm struggling with is where I'm trying to map the SubAccount.Balance and Account.Currency values into the SubAccount.Balance
Money
object.
My mapping classes (below) do the majority of the work but I can't figure out how to build up the Balance
object using the Balance value from the SubAccount table and the Currency value from the Account table.
public class AccountMap : ClassMap<Account>
{
public AccountMap()
{
Table("Account");
Id(x => x.Id)
.Column("AccountId");
Map(x => x.Currency)
.Column("Currency");
}
}
public class SubAccountMap : ClassMap<SubAccount>
{
public SubAccountMap()
{
Table("SubAccount");
Id(x => x.Id)
.Column("AccountId");
References(x => x.Account)
.Column("AccountId");
Component(x => x.Balance,
m =>
{
m.Map(y => y.Value)
.Column("Balance");
m.Map(y => y.Currency)
.Column("Account.Currency"); // <-- This is where I get stuck
});
}
}
Is what I'm trying to do at all possible using Fluent nHibernate?
i dont think its possible, but for a workaround:
public class SubAccount
{
public virtual int Id { get; private set; }
public virtual Account Account { get; private set; }
protected virtual decimal Value { get; set; }
public virtual Money Balance { get { return new Money(Value, Account.Currency); } }
}
public class SubAccountMap : ClassMap<SubAccount>
{
public SubAccountMap()
{
Table("SubAccount");
Id(x => x.Id)
.Column("AccountId");
References(x => x.Account)
.Column("AccountId");
Map(Reveal.Property<decimal>("Value"));
}
}
精彩评论