Code between sessionFactory.openSession() and session.close():
I am not sure what session.clear() does and when I need that? If I removed the bolded line (session.clear();) from the code below, nhibernate would try updating the entity when GetRelatedEmployers is called. Since i restrict the nhibernate user to update in the DB, it will throw an error. However, everything is fine if I leave the session.clear() there. Could someone explain what session.clear does please? Thanks.
Code:
List<Employer> employers = null;
using(EmployerDAO thisDAO = new Employer(123)){
employers = thisDAO.GetRelatedEmployers();
}
Code:
public class EmployerDAO : IDisposable
{
private Employer thisEmployer;
private ISession session;
public Employer ThisEmployer
{
get { return thisCompany; }
}
public EmployerDAO (int employerId)
{
try
{
session = NHibernateSessionHelper.GetCurrentSession();
if (CoId > 0)
{
thisCompany = session.Get<Employer >(employerId);
if (thisCompany == null)
{
throw new NotFoundEmployerException(CoId);
}
//There is a problem if I don't clear the session.
session.Clear();
}
}
catch { throw; }
finally { this.Dispose(); }
}
public List<Employer> GetRelatedEmployers()
{
IList<Employer> relatedEmployers = null;
if (thisEmployer.type!= 0)
{
ICriteria criteria = session.CreateCriteria(typeof(Employer), "employer")
.Add(Expression.Eq("type",thisEmployer.type));
relatedEmployers = criteria.SetMaxResults(4)
.List<Employer>();
}
if (relatedEmployers == null)
{
return new List<Employer>();
}
else
{
return new List<Employer>(relatedEmployers );
}
}
#region IDisposable Members
public void Dispose()
{
if (session.IsOpen)
session.Close();
}
#endregion
}