In Nhibernate, can I further restrict what goes in a one to many using other criteria in the mapping besides the foreign key column?

Go To StackoverFlow.com

1

I've run into a situation where the Table A object needs to map some Table B records as a one to many, but Table B has so many records linked to a particular Table A record that I want to further restrict which records make it into the one to many. This is a legacy database structure which cannot easily be changed because of other legacy programs in production.

Lets say table B looks like this:

TableBPKey (int not null)
TableAFKey (int not null)
TableBColumn1 (char(4) null)
TableBColumn2 (varchar(50) null)

Lets say TableBColumn1 records might contain any of 'N' 4 character codes that classify the table B record in some fashion.

Anyways, lets say I've already mapped the one to many using the TableAFKey column. Can I also tell the mapping that I only want those records where TableBColumn1 == "ABCD" for instance?

Anything using mapping by code would be preferred solution. If it can be done in the old xml mappings but not Mapping by code I'll take that as a solution too.

Thanks!

2012-04-05 00:35
by Isaac Bolinger
Check http://stackoverflow.com/questions/1898303/nhibernate-where-clause-on-one-to-many-relationships-doesnt-work-when-column- - Eranga 2012-04-05 01:41


0

map.Where() is what I wanted. I tested it and it works. You can put an sql expression that would work after an sql Where clause and it would restrict the results that way.

Set<TableBObject>(x => x.TableBRecordsABCDOnly, map =>
            {

                map.Inverse(true);
                map.Cascade(Cascade.All);
                map.Key(k => k.Column(c => c.Name("TableAFKey")));
                map.Where("TableBColumn1 = 'ABCD'");

            },
            action => action.OneToMany());
2012-04-05 01:47
by Isaac Bolinger


1

I believe the "Formula" method on the One-to-many is what you're after. You should be able to use this to specify a additional SQL criteria, for example "is_active = 1".

You can find more info here. http://notherdev.blogspot.com.au/2012/02/mapping-by-code-map.html

(Updated link)

2012-04-05 01:32
by Samuel Fraser
That page is for many to one, not one to many - Isaac Bolinger 2012-04-05 01:46
Oops, try this one instead. http://notherdev.blogspot.com.au/2012/02/mapping-by-code-map.htm - Samuel Fraser 2012-04-05 03:53
I didn't see them mention the .where in ther - Isaac Bolinger 2012-04-05 04:29
Ads