Prabu
Prabu

Reputation: 4187

Attaching a disconnected nHibernate entity to a session and reading from the database

I am new to nHibernate. I have a method which receives a list of disconnected nHibernate entities. In each entity, I have got the primary key set (the primary key is always a field called Id, which is an int).

What I am trying to achieve at this point is to connect to the database and fill each entity up with it's values for that primary key. I am using fluent mappings.

I'm not sure, but is it possible to attach the entity to a session/connection, and some how get the data based on the id generically?

Edit: More concrete info.

I have several nhibernate entities (e.g. User, Account) that inherit from a base class (e.g. EntityBase). This base class contains a common primary key.

I am passing a list of these entities, with the primary key populated.

public void RetrieveEntities(List<EntityBase> entities)

At this point, I would like cycle through these entities and get the full entity from the data source. Is it possible or am approaching this from the wrong way?

If any clarification of the question is required, please leave a comment. Cheers.

Upvotes: 0

Views: 3005

Answers (1)

Jeff Watkins
Jeff Watkins

Reputation: 6359

Use .Merge, this returns an attached version of your passed in Entity.

Something like:

List<EntityBase> attachedEntities = new List<EntityBase>();

foreach(EntityBase entity in entities) 
{
    attachedEntities.Add(session.Merge(entity));
}

Upvotes: 1

Related Questions