我试图弄清楚如何使用 NHibernate 的“性感”通过代码映射系统来映射以下情况。 请帮忙,因为我已经尝试解决这个问题有一段时间了,但没有运气!我正在使用组件来表示组合键。下面是我试图绘制的表格。
Account
-------
BSB (PK)
AccountNumber (PK)
Name
AccountCard
-----------
BSB (PK, FK)
AccountNumber (PK, FK)
CardNumber (PK, FK)
Card
------------
CardNumber (PK)
Status
这是我当前的尝试(根本不起作用!)
帐号:
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")));
}
}
卡片:
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(???)));
}
}
请告诉我这是可能的!
最佳答案
你已经很接近了。
您在 Key
和 ManyToMany
方法的 Action 参数中获取的 IKeyMapper
有一个 Columns
方法可以接受任意数量的参数,因此:
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"))));
关于c# - NHibernate 3.3 : Mapping many to many relationship with composite foreign keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12836288/