Type mismatch on load from second level cache - nhibernate

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)

Related

Sitecore Lucene Search not working after 7.2 update-6 (160123) to 7.5 initial release (141003) upgrade

I upgraded from 7.2 update-6 (160123) to 7.5 initial release (141003)
The issue is search isn't working and I can't rebuild the indexes or do a site publish.
The site is using Lucene.
I got the upgrade files from here:
https://sdn.sitecore.net/Products/Sitecore%20V5/Sitecore%20CMS%207/Update/7_5_rev_141003/Upgrade_Instructions.aspx
I followed the upgrade steps here: https://sdn.sitecore.net/upload/sitecore7/75/xdb_upgrade_and_conversion_guide_sc75-a4.pdf
Updated configs with changes here:
https://sdn.sitecore.net/products/sitecore%20v5/sitecore%20cms%207/releasenotes/webconfig/75_141003.aspx
A few things I tried but didnt resolve:
I re ran all the install steps
We have a custom index which I updated in line with the default web index config, I also tried removing it
I tried overwriting the updated lucene configs with the default ones
from the 7.5 initial install
I disabled the Solr related configs.
The common error appears to be:
Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: type
Source: Sitecore.ContentSearch.Linq
at Sitecore.ContentSearch.Utilities.ReflectionUtility.CreateInstance(Type type)
at Sitecore.ContentSearch.ProviderIndexConfiguration.AddVirtualFieldProcessor(XmlNode configNode)
Log entry when publishing:
7192 03:48:14 INFO Job started: Publish to 'web'
7192 03:48:15 ERROR Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
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 (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Jobs.Job.ThreadEntry(Object state)
Nested Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
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 Sitecore.Configuration.Factory.AssignProperties(Object obj, Object[] properties)
at Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(String configPath, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.CreateFromReference(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(String configPath, String[] parameters, Boolean assert)
at Sitecore.ContentSearch.ContentSearchManager.get_SearchConfiguration()
at Sitecore.ContentSearch.ContentSearchManager.GetIndex(String name)
at Sitecore.Social.BusinessLogic.Search.SearchProvider..ctor()
at DynamicInjectoreb8bc1efd99e4704b4477c9c2ad12999(Object[] )
at Ninject.Activation.Context.Resolve()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.Resolve()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.Resolve()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Sitecore.Social.Client.MessagePosting.Handlers.ItemPublishedHandler.PublishSocialMessages(Object sender, EventArgs args)
at Sitecore.Events.Event.EventSubscribers.RaiseEvent(String eventName, Object[] parameters, EventResult result)
at Sitecore.Events.Event.RaiseEvent(String eventName, Object[] parameters)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(PublishItemContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.Process(PublishContext context)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Publishing.Pipelines.Publish.PublishPipeline.Run(PublishContext context)
at Sitecore.Publishing.Publisher.PublishWithResult()
Nested Exception
Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: type
Source: Sitecore.ContentSearch.Linq
at Sitecore.ContentSearch.Utilities.ReflectionUtility.CreateInstance(Type type)
at Sitecore.ContentSearch.ProviderIndexConfiguration.AddVirtualFieldProcessor(XmlNode configNode)
Log entry when using Indexing manager:
472 04:01:45 ERROR Application error.
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
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 System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
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 Sitecore.Web.UI.Sheer.ClientPage.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Nested Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
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 Sitecore.Configuration.Factory.AssignProperties(Object obj, Object[] properties)
at Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(String configPath, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.CreateFromReference(XmlNode configNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert)
at Sitecore.Configuration.Factory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper)
at Sitecore.Configuration.Factory.CreateObject(String configPath, String[] parameters, Boolean assert)
at Sitecore.ContentSearch.ContentSearchManager.get_SearchConfiguration()
at Sitecore.ContentSearch.Client.Forms.IndexingManagerWizard.BuildIndexes()
Nested Exception
Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: type
Source: Sitecore.ContentSearch.Linq
at Sitecore.ContentSearch.Utilities.ReflectionUtility.CreateInstance(Type type)
at Sitecore.ContentSearch.ProviderIndexConfiguration.AddVirtualFieldProcessor(XmlNode configNode)
After taking another look I found that the social connector module was installed, this adds many config files but the two causing and issue where:
Sitecore.Social.Lucene.Index.Master.config
Sitecore.Social.Lucene.Index.Web.config
These files need to be upgraded or disabled.
The final issue I found was we had an additional config file which doesnt exist in the 7.5 initial release install:
Sitecore.Speak.ContentSearch.Lucene.config
Once i disabled this config in addition to the social connector configs the site began working as expected.

NHibernate missing SqlParameter for overriden property

I'm trying to implement table-per-hierarchy approach, using FluentNHibernate AutoMapping.
I have a base class and three child classes. The third child class overrides a couple of properties of the base class. Instances of first two child classes save fine, but when I try to save an instance of the third class with overridden properties I get
Invalid index 7 for this SqlParameterCollection with Count=7.
It seems NHibernate doesn't add SqlParamaters for overridden properties, but it tries to set a value.
How to fix that? Maybe some changes in mapping/configuration?
The StackTrace:
[IndexOutOfRangeException: Invalid index 7 for this SqlParameterCollection with Count=7.]
System.Data.SqlClient.SqlParameterCollection.RangeCheck(Int32 index) +5033831
System.Data.SqlClient.SqlParameterCollection.GetParameter(Int32 index) +21
System.Data.Common.DbParameterCollection.System.Collections.IList.get_Item(Int32 index) +10
NHibernate.Type.DateTimeType.Set(IDbCommand st, Object value, Int32 index) +74
NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value, Int32 index) +70
NHibernate.Type.NullableType.NullSafeSet(IDbCommand st, Object value, Int32 index, Boolean[] settable, ISessionImplementor session) +37
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object id, Object[] fields, Object rowId, Boolean[] includeProperty, Boolean[][] includeColumns, Int32 table, IDbCommand statement, ISessionImplementor session, Int32 index) +189
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) +498
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session) +166
NHibernate.Action.EntityInsertAction.Execute() +181
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +42
NHibernate.Engine.ActionQueue.ExecuteActions(IList list) +59
NHibernate.Engine.ActionQueue.ExecuteActions() +16
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) +121
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) +92
NHibernate.Impl.SessionImpl.Flush() +291
MDT.Core.DataAccess.DbContext.Flush() in C:\dev\DHL\ISS\Common\MDT.Core\DataAccess\DbContext.cs:215
ISS.Web.Controllers.ReportScheduleController.Index() in C:\dev\DHL\ISS\ISS.Web\Controllers\ReportScheduleController.cs:55
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Yes, FluentNHibernate AutoMapping adds duplicate mapping for overridden properties.
It is strange that the code doesn't help
.Override<ThirdClass>(map => { map.IgnoreProperty(p => p.Age); })
So I have to use
.OverrideAll(map => map.IgnoreProperties(x => x.MemberInfo.HasAttribute<IgnoreMapAttribute>()))
and set [IgnoreMap] attribute in my class.

Invalid value for key 'attachdbfilename' on WebSecurity.InitializeDatabaseConnection

I get this error message when trying to initialize my database connection using SimpleMembership. The first initialize statement goes through, while the second does not. The goal is to use connection strings defined in the Azure service configuration when running Azure emulator or when deployed.
Web.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-**********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-**********.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Azure .cscfg configuration files:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
SimpleMembershipInitializer:
string connectionStringName = "DefaultConnection";
string connectionString = CloudConfigurationManager.GetSetting("SqlConnectionString");
const string userTableName = "UserProfile";
const string providerName = "System.Data.SqlClient";
const string userIdColumn = "UserId";
const string userNameColumn = "UserName";
// This works fine.
// WebSecurity.InitializeDatabaseConnection(connectionStringName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
// This throws exception.
// WebSecurity.InitializeDatabaseConnection(connectionString, providerName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
Environment: Visual Studio 2012, EntityFramework 5.0 and MVC4 RTM with default SimpleMembership structure.
Full stacktrace:
[ArgumentException: Invalid value for key 'attachdbfilename'.]
System.Data.SqlClient.SqlConnectionString.VerifyLocalHostAndFixup(String& host, Boolean enforceLocalHost, Boolean fixup) +888986
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +5330002
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +66
WebMatrix.Data.DbProviderFactoryWrapper.CreateConnection(String connectionString) +96
WebMatrix.Data.<>c__DisplayClass15.<OpenConnectionStringInternal>b__14() +16
WebMatrix.Data.Database.get_Connection() +19
WebMatrix.Data.Database.EnsureConnectionOpen() +12
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +66
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +57
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +49
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionString, String providerName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +63
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:55
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:59
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
MyProject.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:23
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +191
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
It seems to me you might be suffering from the lack of double-escaping (do \\v11.0 instead of \v11.0), as discussed in this post.
I'm ashamed to realize I had a typo in my connection strings. I was getting connection strings from Azure Deployment configuration files, such as:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
The typo was included here, at the start of the value string. It must've been a copy'n'paste bug.
This string was duplicated in Azure configuration files Local.cscfg and Cloud.cscfg, for Azure emulator and Azure deployment respectively, as well as in web.config for running locally outside emulator. The typo was only in the Local.cscfg file, which made me very confused when trying to figure out why it did not work in certain scenarios. In addition the typo was for some reason very hard for me to spot. In hindsight I don't see how I didn't figure this out sooner.
I don't have a solution yet, but here is my own investigation and theory so far:
I took a look at the source code of WebSecurity.InitializeDatabaseConnection() and think maybe I have found a bug. It doesn't seem to ever set the DatabaseConnectionInfo.Type property, which defaults to ConnectionStringName, which could explain why it doesn't like my connection string, since it would interpret it as a connection string name instead.
WebSecurity class:
public static void InitializeDatabaseConnection(string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
WebSecurity.InitializeProviders(new DatabaseConnectionInfo()
{
ConnectionString = connectionString,
ProviderName = providerName
}, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
DatabaseConnectionInfo class:
public Database Connect()
{
switch (this.Type)
{
case DatabaseConnectionInfo.ConnectionType.ConnectionStringName:
return Database.Open(this.ConnectionStringName);
case DatabaseConnectionInfo.ConnectionType.ConnectionString:
return Database.OpenConnectionString(this.ConnectionString, this.ProviderName);
default:
return (Database) null;
}
}
private enum ConnectionType
{
ConnectionStringName,
ConnectionString,
}

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?