2

我试图弄清楚如何使用 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(???)));

    }
}

请告诉我这是可能的!

4

1 回答 1

2

你非常接近。

IKeyMapper您在 theKey和方法的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"))));
于 2012-10-12T03:06:31.567 回答