There are several posts related to this error but I’m running into something different.
Very simple NHibernate scenario. Parent and child tables with one to many relationship. One parent can have multiple children.
I need to delete a Parent record with child records so I put together very basic code which works fine:
var childRecordList = new List<ChildRecord>();
var parentRecord = ParentRecordRepository.Get(parentRecordId);
childRecordList = ChildRecordRepository.GetAll().Where(c=>c.ParentRecord.Id==parentRecord.Id);
foreach(var childRecord in childRecordList)
{
ChildRecordRepository.Delete(childRecord);
}
ParentRecordRepository.Delete(parentRecord);
Works. Deletes child and the parent records.
If I take the logic above and turn it into a Services method as “DeleteRecord(ParentRecord parentRecord)” it starts failing with the Illegal attempt to associate a collection with two open sessions error on ParentRecordRepository.Delete(parentRecord);
Services are called by instantiating a service class and then calling the DeleteRecord method:
var parentRecord = ParentRecordRepository.Get(id);
var recordService = new RecordService();
recordService.DeleteRecord(parentRecord);
Can’t figure out why. Help ?
I tried creating a session by instantiating an instance of the repository and then doing operation on an object pulled from it.
Then I would open a new session of the repository within the Service layer and try to delete the object passed from the controller created session with it. That was the problem.
The bottom line is the same session has to used to both get and delete an object.