NHibernate 3.3:使用复合外键映射多对多关系

时间:2012-10-11 09:22:20

标签: c# nhibernate fluent-nhibernate mapping-by-code

我试图找出如何使用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(???)));

    }
}

请告诉我这是可能的!

1 个答案:

答案 0 :(得分:2)

你非常接近。

您在IKeyMapperKey方法的Action参数中获得的ManyToMany都有一个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"))));