Using NHibernate's ISession.Get<>() w/ a composite key [duplicate]
Asked Answered
C

1

9

I have a composite key in a database table / NHibernate entity. Can I somehow use the .Get method to grab a specific entity or do I have to use HQL / Criteria due to the composite key?

Constabulary answered 16/2, 2010 at 17:40 Comment(0)
D
26

With this composite key mapping:

<class name="MyClass">
    <composite-id>
        <key-property name="Key1" />
        <key-property name="Key2" />
    </composite-id>
    <property name="..." />
</class>

...you can use .Get like this:

var x = Session.Get<MyClass>(new MyClass() { Key1 = 'Foo', Key2 = 'Bar'});
Dextrad answered 28/1, 2011 at 14:36 Comment(2)
This even works with composite IDs that include referenced classes. Just construct the object graph containing the IDs requested.Iniquitous
Just want to mention that this will not work with an anonymous class.Hypercorrection

© 2022 - 2024 — McMap. All rights reserved.