问题
I'm using NHibernate with SQL Server 2005 in a WPF client application.
If I manually stop the SQL Server service and then restart it the session doesn't automatically reconnect.
So far I'm doing this witch seems to work :
try
{
using (ITransaction transaction = this.Session.BeginTransaction())
{
// some select here
}
}catch(Exception ex)
{
if(this.Session.Connection.State == ConnectionState.Closed)
{
try
{
this.Session.Connection.Open();
}
catch (Exception)
{
}
}
}
Is there a better way ?
回答1:
NHibernate won't handle connection drops for you. For occasionally connected scenarios like this I'd look into using a local database as suggested in this question, and then use the Microsoft Sync Framework to synchronize the local and central databases. Also see this related question.
回答2:
If the server just stops, I think there are other problems. I don't have any experience in WPF but there are a lot of questions related to nhibernate / WPF (SO query).
If the database connections drops sometimes you may take a look at the UnitOfWork pattern.
来源:https://stackoverflow.com/questions/2912048/nhibernate-recover-session-after-connection-lost