如何在HasMany中流畅地映射约束

时间:2012-03-16 05:42:49

标签: nhibernate fluent-nhibernate

我是(流利的)nHibernate的新手 我有3张桌子:

•AgencyId(pk)
•AgencyAccountNo

AgencyAccount
•AgencyId(pk)(fk - > Agency.ArtryId)
•AgencyAccountNo(pk)
•ChainId(fk - > AgencyChain.ChainId)

AgencyChain
•ChainId(pk)

AgencyAccount实际上是一个版本控制表。每次代理商使用递增的AgencyAccountNo更改新的AgencyAccount行时。

我正在尝试流畅地映射代理商和代理商链接中的关系,以便只返回Current AgencyAccount,但是遇到了很多麻烦。我已经尝试了很多很多东西,这些东西太多了,无法进入这里,似乎无法找到任何关于此的示例或文档。

你的方法是什么?

1 个答案:

答案 0 :(得分:3)

正常/简单的方式更新

class AgencyMap : ClassMap<Agency>
{
    public AgencyMap()
    {
        Id(a => a.Id);

        Map(a => a.AccountNo);
    }
}

class AgencyAccountMap : ClassMap<AgencyAccount>
{
    public AgencyAccountMap()
    {
        CompositeId()
            .KeyReference(aa => aa.Agency, "AgencyId")
            .KeyProperty(aa => aa.AccountNo, "AgencyAccountNo");

        References(a => a.Chain).Column("chainid");
    }
}

class AgencyChainMap : ClassMap<AgencyChain>
{
    public AgencyChainMap()
    {
        Id(c => c.Id);


        HasMany(c => c.AgencyAccounts)
            .KeyColumn("chainid")
            // to get only the actual AgencyAccounts
            .Where("AgencyAccountNo = (SELECT a.AgencyAccountNo FROM Agency a WHERE a.AgencyId = AgencyId)");

        // or if only interested in Agency (using a Set to prevent duplicates coming from the history of agencyaccounts)
        HasManyToMany(c => c.Agencys)
            .Table("AgencyAccount")
            .ParentKeyColumn("chainid")
            .ChildKeyColumn("agencyid")
            .AsSet();
    }
}

var account = session.Get<AgencyAccount>(new AgencyAccount { Agency = agency, AccountNo = agency.AccountNo });

不使用Identity时的hackish方式,但是其他一些id生成

class AgencyMap : ClassMap<Agency>
{
    public AgencyMap()
    {
        Table("AgencyAccount");
        Id(a => a.Id, "AgencyId").GeneratedBy.Sequence("agency_id_sequence"); // e.g. sequence

        Where("AgencyAccountNo = (SELECT a.AgencyAccountNo FROM Agency a WHERE a.AgencyId = AgencyId)");


        Map(a => a.AccountNo);

        Join("Agency", join =>
        {
            join.KeyColumn("AgencyId");
            join.Map(<some other prop>);
        }
    }
}

注意

  • 这使得为同一个帐户插入新的AgencyAccounts非常困难
  • 无法显示AgencyAccounts的完整历史
  • 可能有很多微妙的问题