I am trying to figure out how to map the following situation using NHibernate's "sexy" mapping by code system. Please help as I have been trying to figure this out for a while with no luck! I am using components to represent the composite keys. Below are the tables I am trying to map.
Account
-------
BSB (PK)
AccountNumber (PK)
Name
AccountCard
-----------
BSB (PK, FK)
AccountNumber (PK, FK)
CardNumber (PK, FK)
Card
------------
CardNumber (PK)
Status
Here is my current attempt (which is not working at all!)
Account:
public class Account
{
public virtual AccountKey Key { get; set; }
public virtual float Amount { get; set; }
public ICollection<Card> Cards { get; set; }
}
public class AccountKey
{
public virtual int BSB { get; set; }
public virtual int AccountNumber { get; set; }
//Equality members omitted
}
public class AccountMapping : ClassMapping<Account>
{
public AccountMapping()
{
Table("Accounts");
ComponentAsId(x => x.Key, map =>
{
map.Property(p => p.BSB);
map.Property(p => p.AccountNumber);
});
Property(x => x.Amount);
Bag(x => x.Cards, collectionMapping =>
{
collectionMapping.Table("AccountCard");
collectionMapping.Cascade(Cascade.None);
//How do I map the composite key here?
collectionMapping.Key(???);
},
map => map.ManyToMany(p => p.Column("CardId")));
}
}
Card:
public class Card
{
public virtual CardKey Key { get; set; }
public virtual string Status{ get; set; }
public ICollection<Account> Accounts { get; set; }
}
public class CardKey
{
public virtual int CardId { get; set; }
//Equality members omitted
}
public class CardMapping : ClassMapping<Card>
{
public CardMapping ()
{
Table("Cards");
ComponentAsId(x => x.Key, map =>
{
map.Property(p => p.CardId);
});
Property(x => x.Status);
Bag(x => x.Accounts, collectionMapping =>
{
collectionMapping.Table("AccountCard");
collectionMapping.Cascade(Cascade.None);
collectionMapping.Key(k => k.Column("CardId"));
},
//How do I map the composite key here?
map => map.ManyToMany(p => p.Column(???)));
}
}
Please tell me this is possible!
You were pretty close.
The IKeyMapper
that you get in the Action parameter of both the Key
and the ManyToMany
methods has a Columns
method that takes as many parameters as you want, so:
collectionMapping.Key(km => km.Columns(cm => cm.Name("BSB"),
cm => cm.Name("AccountNumber")));
//...
map => map.ManyToMany(p => p.Columns(cm => cm.Name("BSB"),
cm => cm.Name("AccountNumber"))));