NHibernate relationships with a shared composite key
I have two tables with composite keys and a linking table between them, like so:
A
- aid (PK)
- sharedkey (PK)
B
- bid (PK)
- sharedkey (PK)
Linking
- aid
- bid
- sharedkey
- sortorder
So the awkward thing there is the shared key, which is part of both FKs. Here's the first thing I tried (I'm using Fluent, but I would have this same problem with XML mappings):
mapping.HasManyToMany(x => x.Bees)
.Table("Linking")
.ParentKeyColumns.Add("aid", "sharedkey")
.ChildKeyColumns.Add("bid", "sharedkey")
.OrderBy("sortorder");
Which gives me an mapping exception: "Repeated column in mapping for collection", because I've put in sharedkey
twice. That makes sense, because I haven't told in NH that I actually want sharedkey
to be the same in each direction.
The Java version of Hibernate has a formula
feature that solves this exactly, but NH, AFAIK, does not. So how开发者_开发知识库 can I map this?
Some caveats:
- It's not totally necessary for this to be in Fluent. XML is fine too
- This is all read-only, so if the solution breaks inserts in some funny way, that's fine
- I can't change the DB at all
a hackish solution could be
public AMap()
{
CompositeId()
.KeyProperty(x => x.Id, "aid")
.KeyProperty(x => x.Name, "sharedkey");
HasManyToMany(x => x.Bees)
.Table("Linking")
.ParentKeyColumns.Add("aid", "sharedkey")
.ChildKeyColumn("bid").ChildPropertyRef("Id")
.OrderBy("sortorder")
;
}
public BMap()
{
CompositeId()
.KeyProperty(x => x.Id, "bid")
.KeyProperty(x => x.Name, "sharedkey");
Map(x => x.Id, "bid")
.Not.Insert();
}
to get all B's this will result in (pseudo sql):
SELECT l.bid FROM a LEFT JOIN linking l ON a.aid = l.aid AND a.sharedkey = l.sharedkey WHERE a.aid = ?
this will get all B with the given aid and the same sharedkey.
精彩评论