Strange NHibernate errors - nhibernate

I'm seeing some strange NHibernate errors that occur sporadically in our production environment, but not on our test servers. Days will go by with no errors, then we'll receive an error that looks as below, and it's as if floodgates have opened and these errors occur all over the place in dozens of different portions of our site. The only way to stop them from happening is to reset the application pool.
We're opening a single session and accompanying transaction for each HTTP request that comes in. It's stored in the HttpContext.Current.Items collection. Each of our repositories extends a base repository class, which references the previously opened session. Here's the module that opens and closes sessions and transactions:
public class NHibernateSessionModule : IHttpModule
{
#region Public Methods
/// <summary>
/// Initializes the http module by hooking up the open session call to the begin
/// request event and the close session call to the end request event.
/// </summary>
/// <param name="context">The context representing the current http request.</param>
public void Init(HttpApplication context)
{
context.BeginRequest += ApplicationBeginRequest;
context.EndRequest += ApplicationEndRequest;
context.Error += OnError;
}
/// <summary>
/// Disposes of the module.
/// </summary>
public void Dispose() { }
#endregion
#region Private Methods
/// <summary>
/// Fired when an error occurs during a request. Cleans up any open sessions and transactions.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private static void OnError(object sender, EventArgs e)
{
var system = HttpContext.Current.Items["SystemSession"] as Lazy<ISession>;
if (system != null && system.IsValueCreated && system.Value != null)
RollbackSession(system.Value);
}
/// <summary>
/// Fired as a request begins. Opens a session and accompanying transaction. Also authenticates the
/// currently logged in user.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private static void ApplicationBeginRequest(object sender, EventArgs e)
{
OpenSession("SystemSession", SessionFactoryProvider.SystemSessionFactory);
}
/// <summary>
/// Opens a new session.
/// </summary>
/// <param name="key">The key used to store the opened session in the current http context.</param>
/// <param name="sessionFactory">The factory used to open the session.</param>
private static void OpenSession(string key, ISessionFactory sessionFactory)
{
if (HttpContext.Current.Items[key] != null)
return;
HttpContext.Current.Items[key] = new Lazy<ISession>(() => {
var session = sessionFactory.OpenSession();
session.BeginTransaction();
return session;
}, true);
}
/// <summary>
/// Fired as a request ends. Closes the previously opened session and commits the session's transaction.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The event arguments.</param>
private static void ApplicationEndRequest(object sender, EventArgs e)
{
var system = HttpContext.Current.Items["SystemSession"] as Lazy<ISession>;
if (system != null && system.IsValueCreated && system.Value != null)
CommitSession(system.Value);
}
/// <summary>
/// Commits a session's transaction.
/// </summary>
/// <param name="session">The session.</param>
private static void CommitSession(ISession session)
{
if (session == null)
return;
if (session.Transaction != null && session.Transaction.IsActive)
{
var transaction = session.Transaction;
try
{
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
session.Close();
}
/// <summary>
/// Rolls back a session's transaction.
/// </summary>
/// <param name="session">The session.</param>
private static void RollbackSession(ISession session)
{
if (session == null)
return;
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Rollback();
session.Close();
}
#endregion
}
Here's the static class used to create ISessionFactory instances:
public class SessionFactoryProvider
{
private static Configuration _configuration;
public static Configuration Configuration
{
get
{
return _configuration;
}
}
public static void Initialize()
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("Database")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMap>())
.ExposeConfiguration(c => _configuration = c)
.BuildSessionFactory();
}
public static void Initialize(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
private static ISessionFactory _sessionFactory;
public static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
Initialize();
return _sessionFactory;
}
}
}
Here's the base repository class:
public class BaseRepository<T>
{
#region Properties
/// <summary>
/// Opens and returns a new session.
/// </summary>
private static ISession OpenSession
{
get
{
if (HttpContext.Current != null)
{
var lazySession = (Lazy<ISession>)HttpContext.Current.Items["SystemSession"];
if (lazySession != null)
return lazySession.Value;
}
TypeContainer.Get<ILog>().Warn("Unable to find session in http context");
throw new InvalidOperationException("The current HTTP context contains no system session.");
}
}
private ISession _session;
public ISession CurrentSession
{
get
{
if (_session == null || !_session.IsOpen || _session.Connection.State == ConnectionState.Closed)
_session = OpenSession;
return _session;
}
}
#endregion
}
Here's a sampling of some of the errors we get:
CustomerID20_
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at NHibernate.Driver.NHybridDataReader.GetOrdinal(String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
The server failed to resume the transaction. Desc:480000000f.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
CustomerID26_
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at NHibernate.Driver.NHybridDataReader.GetOrdinal(String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Type.ManyToOneType.Hydrate(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Type.ComponentType.Hydrate(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Type.ComponentType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
Transaction not connected, or was disconnected
at NHibernate.Transaction.AdoTransaction.CheckNotZombied()
at NHibernate.Transaction.AdoTransaction.Rollback()
at ACC.Web.Modules.NHibernateSessionModule.CommitSession(ISession session)
at ACC.Web.Modules.NHibernateSessionModule.ApplicationEndRequest(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
ID28_0_
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at NHibernate.Driver.NHybridDataReader.GetOrdinal(String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
Transaction not successfully started
at NHibernate.Transaction.AdoTransaction.CheckBegun()
at NHibernate.Transaction.AdoTransaction.Rollback()
at ACC.Web.Modules.NHibernateSessionModule.CommitSession(ISession session)
at ACC.Web.Modules.NHibernateSessionModule.ApplicationEndRequest(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
col_0_0_
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at NHibernate.Driver.NHybridDataReader.GetOrdinal(String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.GetResultColumnOrRow(Object[] row, IResultTransformer resultTransformer, IDataReader rs, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
The server failed to resume the transaction. Desc:8040000001d.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
Many of the above errors have inner exception messages like:
System.InvalidOperationException: Invalid attempt to call Read when reader is closed.
System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
System.Data.SqlClient.SqlException: New request is not allowed to start because it should come with valid transaction descriptor.
System.IndexOutOfRangeException: ID28_0_
NHibernate.AssertionFailure: possible non-threadsafe access to the session
System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is open.
Lots of these errors appear as though a session is being opened, accessed or closed across multiple threads, but we're not spawning any other threads that access the database anywhere in the application.
Looking through the logs of the NHibernate Profiler tells us that transactions are being opened and committed/rolled back in every case.
We've been trying to fix this problem for some time now and have run out of ideas. Has anyone run into this problem before? Any ideas?
Thanks!
Chris

We're not using NHibernate, so I'm not sure how applicable this is, but we were getting tons of GetOrdinal errors daily. Datareaders and datatables were coming back with unexpected data (i.e. from an entirely different query than we expected). I recently discovered the "Enlist" connection string argument, and after adding "Enlist=False" to all of our connection strings, we've not thrown a single GetOrdinal error.
I believe this change will probably fix alot of the similar issues people have reported here and elsewhere.
Mike

Related

Type mismatch on load from second level cache

I have a clustered web app running in asp.net + nhibernate that relies in MemcacheD as its second level cache provider. Everything ran fine for months and today some queries started to give a type mismatch error when loading entities from cache L2. Restarting the cache appeared to solve the problem, but a few minutes later the error returned. Right now the cache is disabled and everything is working.
Any clue is appreciated.
Stacktrace:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.
---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> NHibernate.TypeMismatchException: Provided id of the wrong type. Expected: System.Int32, got System.Int64
at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.InternalLoad(String entityName, Object id, Boolean eager, Boolean isNullable)
at NHibernate.Type.EntityType.ResolveIdentifier(Object id, ISessionImplementor session)
at NHibernate.Type.TypeFactory.Assemble(Object[] row, ICacheAssembler[] types, ISessionImplementor session, Object owner)
at NHibernate.Cache.Entry.CacheEntry.Assemble(Object[] values, Object result, Object id, IEntityPersister persister, IInterceptor interceptor, ISessionImplementor session)
at NHibernate.Event.Default.DefaultLoadEventListener.AssembleCacheEntry(CacheEntry entry, Object id, IEntityPersister persister, LoadEvent event)
at NHibernate.Event.Default.DefaultLoadEventListener.LoadFromSecondLevelCache(LoadEvent event, IEntityPersister persister, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.InternalLoad(String entityName, Object id, Boolean eager, Boolean isNullable)
at NHibernate.Type.EntityType.ResolveIdentifier(Object id, ISessionImplementor session)
at NHibernate.Engine.TwoPhaseLoad.InitializeEntity(Object entity, Boolean readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent)
at NHibernate.Loader.Loader.InitializeEntitiesAndCollections(IList hydratedObjects, Object resultSetId, ISessionImplementor session, Boolean readOnly)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Impl.SessionImpl.ListCustomQuery(ICustomQuery customQuery, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List(NativeSQLQuerySpecification spec, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List[T](NativeSQLQuerySpecification spec, QueryParameters queryParameters)
at NHibernate.Impl.SqlQueryImpl.List[T]() at Punchclock.DAL.NHibernate.UserDAO.GetUserList(QueryUser pQueryUser, Nullable`1 pTop)
at Punchclock.Biz.UserBiz.GetUserList(QueryUser queryUser, Nullable`1 pTop) at Punchclock.Biz.UserBiz.GetUserList(QueryUser queryUser, Int32 pTop)
at Punchclock.Net.Service.UserService.GetUserList(QueryUser queryUser, Int32 pTop)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at Punchclock.Net.Service.ServiceProxy`1.Invoke(IMessage msg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Punchclock.Core.Service.IUserService.GetUserList(QueryUser queryUser, Int32 pTop)
at Punchclock.Net.Delegate.UserDelegate.GetUserList(QueryUser queryUser, Int32 pTop)
at Punchclock.Client.Controller.UcUserQueryController.GetUserList(QueryUser queryUser, Int32 pTop)
at Punchclock.Client.Web.Record.UserControls.UcUserQuery.MakeQuery(Int32 maxResults)
at Punchclock.Client.Web.UserControls.UcQueryBase.OnQueryButtonClick(Object o, QueryEventArgs e)
at Punchclock.Client.Web.Record.UserControls.UcUserQuery.btnQuery_Click(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
--- End of inner exception stack trace ---
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.forms_query_aspx.ProcessRequest(HttpContext context)
in c:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\punchclock_rc1\c4ca2e53\49a32ae2\App_Web_hfudjjsj.2.cs:line 0
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

How to deal with TIME datatype from SQL Server 2008 with NHibernate?

I am using the TIME datatype from SQL Server 2008 and I am having some problems getting it to work with NHibernate.
public TimeTableEventMap()
{
Id(x => x.Id)
Map(x => x.Day).NvarcharWithMaxSize().Not.Nullable();
Map(x => x.StartTime).Length(4).TimeDataType().Not.Nullable();
Map(x => x.Endtime).Length(4).TimeDataType().Not.Nullable();
References(x => x.TimeTable).Not.Nullable().Cascade.All();
References(x => x.RequiredSettings).Not.Nullable().Cascade.All();
}
/// <summary>
/// MS Sql 2008 date type.
/// </summary>
/// <param name="map"></param>
/// <returns></returns>
public static PropertyPart TimeDataType(this PropertyPart map)
{
return map.CustomSqlType("time");
}
public class TimeTableEvent
{
public virtual int Id { get; private set; }
public virtual DayOfWeek Day { get; set; }
public virtual DateTime StartTime { get; set; }
public virtual DateTime Endtime { get; set; }
public virtual TimeTable TimeTable { get; set; }
public virtual RequiredSetting RequiredSettings { get; set; }
}
I get this error
NHibernate.Exceptions.GenericADOException was caught
Message=could not execute query
[ SELECT TOP (#p0) this_.TimeTableEventId as TimeTabl1_15_1_,
this_.Day as Day15_1_, this_.StartTime as StartTime15_1_,
this_.Endtime as Endtime15_1_, this_.TimeTableId as TimeTabl5_15_1_,
this_.RequiredSettingsId as Required6_15_1_,
requiredse2_.RequiredSettingsId as Required1_10_0_,
requiredse2_.BackgroundColor as Backgrou2_10_0_, requiredse2_.Title as
Title10_0_ FROM TimeTableEvents this_ inner join RequiredSettings
requiredse2_ on
this_.RequiredSettingsId=requiredse2_.RequiredSettingsId WHERE
this_.TimeTableId in (#p1) ]
Positional parameters: #0>14
[SQL: SELECT TOP (#p0) this_.TimeTableEventId as TimeTabl1_15_1_,
this_.Day as Day15_1_, this_.StartTime as StartTime15_1_,
this_.Endtime as Endtime15_1_, this_.TimeTableId as TimeTabl5_15_1_,
this_.RequiredSettingsId as Required6_15_1_,
requiredse2_.RequiredSettingsId as Required1_10_0_,
requiredse2_.BackgroundColor as Backgrou2_10_0_, requiredse2_.Title as
Title10_0_ FROM TimeTableEvents this_ inner join RequiredSettings
requiredse2_ on
this_.RequiredSettingsId=requiredse2_.RequiredSettingsId WHERE
this_.TimeTableId in (#p1)]
Source=NHibernate
SqlString=SELECT TOP (#p0) this_.TimeTableEventId as
TimeTabl1_15_1_, this_.Day as Day15_1_, this_.StartTime as
StartTime15_1_, this_.Endtime as Endtime15_1_, this_.TimeTableId as
TimeTabl5_15_1_, this_.RequiredSettingsId as Required6_15_1_,
requiredse2_.RequiredSettingsId as Required1_10_0_,
requiredse2_.BackgroundColor as Backgrou2_10_0_, requiredse2_.Title as
Title10_0_ FROM TimeTableEvents this_ inner join RequiredSettings
requiredse2_ on
this_.RequiredSettingsId=requiredse2_.RequiredSettingsId WHERE
this_.TimeTableId in (#p1)
StackTrace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor
session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor
session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor
session, QueryParameters queryParameters, ISet1 querySpaces, IType[]
resultTypes)
at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor
session)
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria,
IList results)
at NHibernate.Impl.CriteriaImpl.List(IList results)
at NHibernate.Impl.CriteriaImpl.List[T]()
at NHibernate.Criterion.QueryOver1.ListU
at NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver.ListU
at TimeTableRepo.cs:line 47
at TimeTableService.cs:line 43
InnerException: System.FormatException
Message=Input string '16:00:00' was not in the correct
format.
Source=NHibernate
StackTrace:
at NHibernate.Type.DateTimeType.Get(IDataReader rs,
Int32 index)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[]
names, ISessionImplementor session, Object owner)
at NHibernate.Type.AbstractType.Hydrate(IDataReader
rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Persister.Entity.AbstractEntityPersister.Hydrate(IDataReader
rs, Object id, Object obj, ILoadable rootLoadable, String[][]
suffixedPropertyColumns, Boolean allProperties, ISessionImplementor
session)
at NHibernate.Loader.Loader.LoadFromResultSet(IDataReader rs, Int32 i,
Object obj, String instanceClass, EntityKey key, String rowIdAlias,
LockMode lockMode, ILoadable rootPersister, ISessionImplementor
session)
at NHibernate.Loader.Loader.InstanceNotYetLoaded(IDataReader dr, Int32 i,
ILoadable persister, EntityKey key, LockMode lockMode, String
rowIdAlias, EntityKey optionalObjectKey, Object optionalObject, IList
hydratedObjects, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRow(IDataReader rs,
ILoadable[] persisters, EntityKey[] keys, Object optionalObject,
EntityKey optionalObjectKey, LockMode[] lockModes, IList
hydratedObjects, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet,
ISessionImplementor session, QueryParameters queryParameters,
LockMode[] lockModeArray, EntityKey optionalObjectKey, IList
hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session,
QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor
session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor
session, QueryParameters queryParameters)
InnerException: System.InvalidCastException
Message=Unable to cast object of type
'System.TimeSpan' to type 'System.IConvertible'.
Source=mscorlib
public List<TimeTableEvent> GetTimeTableEvents(Student student, List<int> timeTableIds)
{
TimeTableEvent tAlias = null;
List<TimeTableEvent> allEvents = session.QueryOver<TimeTableEvent>(() => tAlias)
.Where(Restrictions.In(Projections.Property(() => tAlias.TimeTable.Id), timeTableIds))
.Fetch(r => r.RequiredSettings).Eager
.TransformUsing(Transformers.DistinctRootEntity)
.Take(QueryLimits.TimeTableEvents)
.List<TimeTableEvent>().ToList();
return allEvents;
}
Date/Time Support in NHibernate
You should use the TimeSpan type on the .NET side of things instead of DateTime (since there is no Date) like Dotjoe said in his comment.
To put VahidN's answer explicitly, when you have an error message that says
Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'.
It means the property you're trying to map to should be a TimeSpan instead of a DateTime. Same deal with DateTimeOffset.
A partial solution which I found useful is to use formula=CONVERT(DateTime, <ColumnName>) in the mapping.
The significant downside is that this is only useful for read-only access.

Nhibernate creating unusual SQL for a basic Query

The following is from the open source project Funnelweb. I am in the process of converting it from SQL Express to SQL CE 4.0. The SQL that is sent to the database contains logical OR ( || ). This results in the SQL error. Can anyboy explain why this would be happening?
FLuenbt Nhibernate Mapping
public class TagMapping : ClassMap<Tag>
{
public TagMapping()
{
Id(x => x.Id);
Map(x => x.Name);
HasManyToMany(x => x.Entries)
.Table("TagItem")
.ParentKeyColumn("TagId")
.ChildKeyColumn("EntryId")
.AsSet()
.Inverse()
.LazyLoad();
}
}
public IQueryable<Tag> GetTags(string tagName)
{
tagName = tagName ?? string.Empty;
return from tag in session.Query<Tag>()
where tag.Name.Contains(tagName)
select tag;
}
SQL that it sent to query the database
select tag0_.Id as Id7_, tag0_.Name as Name7_ from "Tag" tag0_ where tag0_.Name like ('%'||#p0||'%')
Stack Trace
NHibernate.Exceptions.GenericADOException was unhandled by user code
Message=could not execute query
[ select tag0_.Id as Id7_, tag0_.Name as Name7_ from "Tag" tag0_ where tag0_.Name like ('%'||#p0||'%') ]
Name:p1 - Value:
[SQL: select tag0_.Id as Id7_, tag0_.Name as Name7_ from "Tag" tag0_ where tag0_.Name like ('%'||#p0||'%')]
Source=NHibernate
SqlString=select tag0_.Id as Id7_, tag0_.Name as Name7_ from "Tag" tag0_ where tag0_.Name like ('%'||#p0||'%')
StackTrace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters parameters)
at NHibernate.Impl.ExpressionQueryImpl.List()
at NHibernate.Linq.NhQueryProvider.ExecuteQuery(NhLinqExpression nhLinqExpression, IQuery query, NhLinqExpression nhQuery)
at NHibernate.Linq.NhQueryProvider.Execute(Expression expression)
at NHibernate.Linq.NhQueryProvider.Execute[TResult](Expression expression)
at Remotion.Data.Linq.QueryableBase`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at FunnelWeb.Web.Areas.Admin.Views.WikiAdmin.EditModel..ctor(PageName page, Int32 originalEntryId, IEnumerable`1 tags) in C:\Projects\oss\funnelweb\src\FunnelWeb.Web\Areas\Admin\Views\WikiAdmin\EditModel.cs:line 24
at FunnelWeb.Web.Areas.Admin.Controllers.WikiAdminController.Edit(PageName page, Nullable`1 revertToRevision) in C:\Projects\oss\funnelweb\src\FunnelWeb.Web\Areas\Admin\Controllers\WikiAdminController.cs:line 52
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException: System.Data.SqlServerCe.SqlCeException
Message=There was an error parsing the query. [ Token line number = 1,Token line offset = 91,Token in error = | ]
Source=SQL Server Compact ADO.NET Data Provider
ErrorCode=-2147467259
HResult=-2147217900
NativeError=25501
StackTrace:
at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)
at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlServerCe.SqlCeCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
InnerException:
Try subclassing the MsSqlCe[40]Dialect and adding the following line in the constructor:
RegisterFunction("concat",
new VarArgsSQLFunction(NHibernateUtil.String, "(", "+", ")"));
If it works, please open a Jira ticket (http://jira.nhforge.org) with it as a patch to MsSqlCeDialect.

Why is my NHibernate query failing with an IndexOutOfRangeException?

I am using Fluent NHibernate and in certain cases my query is failing with a System.IndexOutOfRangeException.
It seems that the issue has to do with the combination of using escaped column name(s) in the mapping and calling CreateSQLQuery().AddEntity(). It works fine if none of the columns need escaping or if I instead use CreateCriteria<Employee>().
public class Employee {
public virtual string EmployeeNumber { get; set; }
public virtual string Username { get; set; }
}
public class EmployeeMapping : ClassMap<Employee> {
public EmployeeMapping() {
Table("Employees");
Id(e => e.EmployeeNumber)
.Column("No_");
Map(e => e.Username)
.Column("`E-mail Login`"); // Note the escaped column name
}
}
public class SqlRepository {
...
public IList<Employee> ListEmployees() {
using (ISession session = _sessionBuilder.GetSession()) {
return session
.CreateSQLQuery("SELECT No_, [E-mail Login] FROM Employees")
.AddEntity(typeof(Employee))
.List<Employee>();
}
}
}
Calling ListEmployees() results in a System.IndexOutOfRangeException.
However, if I change the CreateSQLQuery().AddEntity() call to CreateCriteria<Employee>(), it works fine. But my actual SQL is more complex so I don't think that will work for me.
Or, if I change the Username mapping to Map(e => e.Username).Column("Username"); and change the SQL query to SELECT No_, [E-mail Login] AS Username FROM Employees, it works fine. But this would break the mapping for other places in my code that do use CreateCriteria<Employee>(). And I can't change the table schema at the moment.
Why is this failing? Do you have any other suggestions besides what I mentioned? Thanks.
I am using Fluent NHibernate 1.0, NHibernate 2.1.0.4000 and SQL Server 2005.
Here is the stack trace:
NHibernate.ADOException was unhandled
Message="could not execute query\r\n[ SELECT No_, [E-mail Login] FROM Employees ]\r\n[SQL: SELECT No_, [E-mail Login] FROM Employees]"
Source="NHibernate"
SqlString="SELECT No_, [E-mail Login] FROM Employees"
StackTrace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes)
at NHibernate.Loader.Custom.CustomLoader.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Impl.SessionImpl.ListCustomQuery(ICustomQuery customQuery, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List(NativeSQLQuerySpecification spec, QueryParameters queryParameters, IList results)
at NHibernate.Impl.SessionImpl.List[T](NativeSQLQuerySpecification spec, QueryParameters queryParameters)
at NHibernate.Impl.SqlQueryImpl.List[T]()
at NHibernateTest.Core.SqlRepository.ListEmployees() in C:\dev\NHibernateTest\NHibernateTest\SqlRepository.cs:line 14
at NHibernateTest.Console.Program.Main(String[] args) in C:\dev\NHibernateTest\NHibernateTest.Console\Program.cs:line 8
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.IndexOutOfRangeException
Message="[E-mail Login]"
Source="System.Data"
StackTrace:
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at NHibernate.Driver.NHybridDataReader.GetOrdinal(String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Type.AbstractType.Hydrate(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Persister.Entity.AbstractEntityPersister.Hydrate(IDataReader rs, Object id, Object obj, ILoadable rootLoadable, String[][] suffixedPropertyColumns, Boolean allProperties, ISessionImplementor session)
at NHibernate.Loader.Loader.LoadFromResultSet(IDataReader rs, Int32 i, Object obj, String instanceClass, EntityKey key, String rowIdAlias, LockMode lockMode, ILoadable rootPersister, ISessionImplementor session)
at NHibernate.Loader.Loader.InstanceNotYetLoaded(IDataReader dr, Int32 i, ILoadable persister, EntityKey key, LockMode lockMode, String rowIdAlias, EntityKey optionalObjectKey, Object optionalObject, IList hydratedObjects, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRow(IDataReader rs, ILoadable[] persisters, EntityKey[] keys, Object optionalObject, EntityKey optionalObjectKey, LockMode[] lockModes, IList hydratedObjects, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
InnerException:
I got it to work by using aliases for the column names and using a result transformer. It's not ideal since it ignores my mapping and requires setting an alias for each column. But it works for now.
public class SqlRepository {
...
public IList<Employee> ListEmployees() {
using (ISession session = _sessionBuilder.GetSession()) {
return session
.CreateSQLQuery(#"
SELECT No_ AS EmployeeNumber, [E-mail Login] AS Username
FROM Employees")
.AddScalar("EmployeeNumber", NHibernateUtil.String)
.AddScalar("Username", NHibernateUtil.String)
.SetResultTransformer(Transformers.AliasToBean<Employee>())
.List<Employee>();
}
}
}
Any better solutions? Could there be a bug in (Fluent) NHibernate causing the original issue?

Mapped Objectified relationship with nhibernate can not initialize collection

I'm mapping a objectified relationship (the many->many mapping table contains properties),
following this guide.
The SQL generated(see exception) is working and returns what i want(strictly speaking it should have been an inner join?).
But I get a GenericADOException saying:
could not initialize a collection: [Questionnaires.Core.Questionnaire.Questions#CBDEDAFC183B4CD7AF1422423A91F589][SQL: SELECT questions0_.ida_questionnaire_id as ida4_2_, questions0_.ida_questionnaire_question_id as ida1_2_, questions0_.ida_questionnaire_question_id as ida1_5_1_, questions0_.question_no as question2_5_1_, questions0_.ida_question_id as ida3_5_1_, questions0_.ida_questionnaire_id as ida4_5_1_, question1_.ida_question_id as ida1_3_0_, question1_.ida_question_type_id as ida2_3_0_, question1_.description as descript3_3_0_, question1_.validate_max as validate4_3_0_, question1_.validate_min as validate5_3_0_ FROM ida_questionnaire_question questions0_ left outer join ida_question question1_ on questions0_.ida_question_id=question1_.ida_question_id WHERE questions0_.ida_questionnaire_id=?]
I'm guessing this is because Questionnaire is really mapping to QuestionnaireQuestion not Question(Questionnaire->hasMany->QuestionnaireQuestion<-hasMany<-Question). But I can't seem to find a way of going around this.
Question:
public class Question : PersistentObjectWithTypedId<string>
{
#region Constructors
public Question()
{
Alternatives = new List<Alternative>();
Questionnaires = new List<Questionnaire>();
}
public Question(string description)
: this()
{
Check.Require(!string.IsNullOrEmpty(description) && description.Trim() != string.Empty);
Description = description;
}
#endregion
#region Properties
public virtual string Type { get; set; }
public virtual string Description { get; set; }
public virtual int Order { get; set; }
public virtual IList<Questionnaire> Questionnaires { get; set; }
public virtual IList<Alternative> Alternatives { get; set; }
public virtual Validator MyValidator { get; set; }
}
public class QuestionMap : ClassMap<Question>
{
public QuestionMap()
{
WithTable("ida_question");
Id(x => x.ID, "ida_question_id").WithUnsavedValue(0).GeneratedBy.UuidHex("");
Map(x => x.Description, "description").AsReadOnly();
Map(x => x.Type, "ida_question_type_id").AsReadOnly();
Component<Core.Validator>(x => x.MyValidator, m =>
{
m.Map(x => x.Type, "ida_question_type_id");
m.Map(x => x.RangeMin, "validate_min");
m.Map(x => x.RangeMax, "validate_max");
});
HasMany<QuestionnaireQuestion>(x => x.Questionnaires)
.Cascade.AllDeleteOrphan()
.WithKeyColumn("ida_question_id");
HasMany<Alternative>(x => x.Alternatives)
.IsInverse()
.WithKeyColumn("ida_question_id")
.AsBag().SetAttribute("cascade", "all");
}
}
QuestionnaireQuestion:
public class QuestionnaireQuestion : PersistentObjectWithTypedId<string>
{
protected QuestionnaireQuestion()
{
}
public virtual int QuestionOrder { get; set; }
public virtual Question Question {get;set;}
public virtual Questionnaire Questionnaire { get; set; }
}
public class QuestionnaireQuestionMap : ClassMap<QuestionnaireQuestion>
{
public QuestionnaireQuestionMap()
{
WithTable("ida_questionnaire_question");
SetAttribute("lazy", "false");
Id(x => x.ID, "ida_questionnaire_question_id")
.WithUnsavedValue(0)
.GeneratedBy.UuidHex("");
References(x => x.Question, "ida_question_id")
.WithForeignKey("ida_question_id")
.FetchType.Join();
References(x => x.Questionnaire, "ida_questionnaire_id")
.WithForeignKey("ida_questionnaire_id")
.FetchType.Join();
Map(x => x.QuestionOrder, "question_no");
}
}
Questionnaire:
public class Questionnaire : PersistentObjectWithTypedId<string>
{
#region Constructors
public Questionnaire()
{
Questions = new List<Question>();
}
public Questionnaire(string description) : this()
{
Check.Require(!string.IsNullOrEmpty(description) && description.Trim() != string.Empty);
Description = description;
}
#endregion
#region Properties
public virtual string Description { get; set; }
public virtual IList<Question> Questions { get; set; }
#endregion
}
public class QuestionnaireMap : ClassMap<Questionnaire>
{
public QuestionnaireMap(){
WithTable("ida_questionnaire");
SetAttribute("lazy", "false");
Id(x => x.ID, "ida_questionnaire_id")
.WithUnsavedValue(0)
.GeneratedBy.UuidHex("");
Map(x => x.Description);
HasMany<QuestionnaireQuestion>(x => x.Questions)
.Cascade.AllDeleteOrphan()
.WithKeyColumn("ida_questionnaire_id");
}
}
The result of running the SQL in the exception in the DB is 6 rows (the expected number) containing:
IDA4_2_: Guids
IDA1_2_: Guids
IDA1_5_1_: Guids
QUESTION2_5_1: Number (order
property)
IDA3_5_1_: Guids
IDA4_5_1: Guids
IDA1_3_0_: Guids
IDA2_3_0_: MOBILEPHONE (type
property)
DESCRIPT3_3_0_: mobiltelefon
(Description property)
VALIDATE4_3_0_: (RangeMin property)
VALIDATE5_3_0_: (RangeMax property)
The complete exception is:
[InvalidCastException: Cant use object type Questionnaires.Core.QuestionnaireQuestion as Questionnaires.Core.Question.]
NHibernate.Collection.Generic.PersistentGenericBag`1.ReadFrom(IDataReader reader, ICollectionPersister persister, ICollectionAliases descriptor, Object owner) +160
NHibernate.Loader.Loader.ReadCollectionElement(Object optionalOwner, Object optionalKey, ICollectionPersister persister, ICollectionAliases descriptor, IDataReader rs, ISessionImplementor session) +407
NHibernate.Loader.Loader.ReadCollectionElements(Object[] row, IDataReader resultSet, ISessionImplementor session) +412
NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +472
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1010
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +114
NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type) +362
[GenericADOException: could not initialize a collection: [Questionnaires.Core.Questionnaire.Questions#CBDEDAFC183B4CD7AF1422423A91F589][SQL: SELECT questions0_.ida_questionnaire_id as ida4_2_, questions0_.ida_questionnaire_question_id as ida1_2_, questions0_.ida_questionnaire_question_id as ida1_5_1_, questions0_.question_no as question2_5_1_, questions0_.ida_question_id as ida3_5_1_, questions0_.ida_questionnaire_id as ida4_5_1_, question1_.ida_question_id as ida1_3_0_, question1_.ida_question_type_id as ida2_3_0_, question1_.description as descript3_3_0_, question1_.validate_max as validate4_3_0_, question1_.validate_min as validate5_3_0_ FROM ida_questionnaire_question questions0_ left outer join ida_question question1_ on questions0_.ida_question_id=question1_.ida_question_id WHERE questions0_.ida_questionnaire_id=?]]
NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type) +528
NHibernate.Loader.Collection.CollectionLoader.Initialize(Object id, ISessionImplementor session) +74
NHibernate.Persister.Collection.AbstractCollectionPersister.Initialize(Object key, ISessionImplementor session) +59
NHibernate.Event.Default.DefaultInitializeCollectionEventListener.OnInitializeCollection(InitializeCollectionEvent event) +573
NHibernate.Impl.SessionImpl.InitializeCollection(IPersistentCollection collection, Boolean writing) +150
NHibernate.Collection.AbstractPersistentCollection.ForceInitialization() +287
NHibernate.Engine.StatefulPersistenceContext.InitializeNonLazyCollections() +213
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +171
NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister) +493
NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) +82
NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) +54
NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) +206
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +133
NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +948
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +436
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +236
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +1303
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +125
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +145
NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) +66
NHibernate.Impl.SessionImpl.Get(Object id) +91
SharpArch.Data.NHibernate.RepositoryWithTypedId`2.Get(IdT id) +152
Questionnaires.Controllers.QuestionnaireController.Create(String username, String id) in C:\Documents and Settings\berbor\Mine dokumenter\Visual Studio 2008\Projects\Questionnaires\Questionnaires.Controllers\QuestionnaireController.cs:40
lambda_method(ExecutionScope , ControllerBase , Object[] ) +205
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.b__7() +52
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +254
System.Web.Mvc.<>c__DisplayClassc.b__9() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +350
System.Web.Mvc.Controller.ExecuteCore() +110
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +119
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +41
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
As for the reason I'm doing this:
One Questionnaire may have many Questions, One Question may have many Questionnaire.
I want to be able to give Questions some properties dependent on context (which Questionnaire is in), one question may be required in one questionnaire but not another etc. It's more than just order, that was just an example trying to keep it simple.
The exception is when trying to load data into Questionnaire.IList<Question>. And it's still thrown after I modify my IList<Questionnaire> to IList<QuestionnaireQuestion> and the respective mappings.
The problem then would be that Questionnaire.Questions is mapped as containing QuestionnaireQuestion but is of type Question. But if I try to map it as containing QuestionnaireQuestion my SQL does no join at all and it still fails.
Is this what I should do, just that I'm doing it wrong?
In the example I read he does it like I did as far as I can see, only difference is the newer version of FluentNhibernate that now uses Generics. So I need to specify the correct type.
Then, you should not have a List of Questionnaires in your Question class, but a List of QuestionnaireQuestion objects.
Are you sure you receive an ADO.NET Exception ?
Can you execute the generated query against your database ?
I don't understand your situation however, what is this QuestionairreQuestion class ? You're not using it in your Question class ?
I understand that you want to have an order in which your questions should occur.
So, if you have extra properties , I think you should use the QuestionairreQuestion class in your Question class.
But, if you only have this QuestionairreQuestion class in order to enforce an 'order' (and no other attributes), then, you could maybe use another Collection-Type instead of an IList.
There are collections in NHibernate which allow you to have ordered-collections (a map , for instance). So, you could use this collection in your Question class to hold Questionairre objects.
(ps: nhibernate generates an outer join, because you didn't specify in your mapping that the collection should not be null. So, an outer join is used because in some circumstances, it could be possible that you have a Question without Questionaires, as far as nhibernate is concerned).