Problem using nHibernate 2.0 Session.Get <T> for a class with a composite identifier
I am having problems with something that (I think) should be simple but cannot find any clear information.
In a scenario where I have three tables describing a domain in which a person can have several tasks:
Person - has PersonId, Name
Job - has JobId, JobName
PersonJob - has PersonId, JobId, YearsOfEmployment
Note. In my object model, I have entities representing each table. I have this third object to represent the Person / Job relationship, because it has useful metadata (YearsOfEmployment) and not just a simple join table.
So, if I knew PersonId and JobId, is there an easy way to use a session and return an object corresponding to these identifiers?
Or, in another way, because I already know that primary keys are a dead brain, an easy way I can turn SQL "SELECT YearsOfEmployment FROM PersonJob WHERE PersonId = 1 AND JobId = 1" into something like:
var keys = new {PersonId=1, JobId=2};
PersonJob obj = Session.Get<PersonJob>(keys);
By the way: the cards would look something like this:
<class name="Person" table="dbo.Person" lazy="true">
<id name="PersonId">
<generator class="native"/>
</id>
<property name="Name"/>
</class>
<class name="Job" table="dbo.Job" lazy="true">
<id name="JobId">
<generator class="native"/>
</id>
<property name="JobName"/>
</class>
<class name="PersonJob" table="dbo.PersonJob" lazy="true">
<composite-id>
<key-property name="PersonId"></key-property>
<key-property name="JobId"></key-property>
</composite-id>
<property name="YearsOfEmployment"/>
</class>
Ok, I answered my question. I think posting your problem is almost as painful as talking to someone. If I were to create a composite PersonJob identifier for a component or class, i.e.
<class name="PersonJob" table="dbo.PersonJob" lazy="true">
<composite-id name="PersonJobKey" class="PersonJobKey">
<key-property name="PersonId"></key-property>
<key-property name="JobId"></key-property>
</composite-id>
</class>
Then I can just do this:
PersonJobKey key = new PersonJobKey() { PersonId = 1, JobId = 1 };
PersonJob obj = Session.Get<PersonJob>(key);
int yearsOfEmployment = obj.YearsOfEmployment;
cool. hope this helps someone else figure it out ...
, , , . , . - :
Session.Get<SalesRepArea>(new { AreaCode = "ACode", RegionCode = "RCode"});
, nHibernate , , . , nHibernate Get , , , ( , equals #, ). ,
<class name="SalesRepArea">
<composite-id>
<key-property
name="AreaCode" column="AreaCode" type="String" length="12" />
<key-property
name="RegionCode" column="RegionCode" type="String" length="12" />
</composite-id>
, ,
SalesRepArea myArea = Session.Get<SalesRepArea>(
new SalesRepArea()
{
AreaCode = "ACode",
RegionCode = "RCode"
}
);
, , , , Hibernate , , .
, , , , .
,