How to Fluently map with constraint in HasMany

痞子三分冷 提交于 2019-12-12 03:10:07

问题


I’m new to (fluent) nHibernate.
I have 3 tables:
Agency
• AgencyId (pk)
• AgencyAccountNo

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

AgencyChain
• ChainId (pk)

AgencyAccount is effectively a versioning table. Everytime an Agency changes a new AgencyAccount row with an incremented AgencyAccountNo.

I am trying to fluently map the relationships in Agency and AgencyChain so that only the Current AgencyAccount will be returned, but have had a lot of trouble. I have tried many, many things, too numerous to go into here, and can’t seem to find any examples or documentation on this.

What would your approach be?


回答1:


the normal/easy way Updated

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 });

the hackish way when not using Identity but some other id generation

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>);
        }
    }
}

Note:

  • this makes inserting new AgencyAccounts for the same Account very difficult
  • cant show the complete history of AgencyAccounts
  • possibly has a lot of subtle problems


来源:https://stackoverflow.com/questions/9732508/how-to-fluently-map-with-constraint-in-hasmany

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!