ef core sqlconnection tryopen nullreferenceexception - connection-string

I am getting a strange error when I used a pre-built (in our custom base) db context I get the following exception
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(Boolean buffer)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at lambda_method(Closure , QueryContext )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_1`1.<CompileQueryCore>b__0(QueryContext qc)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
...(ommitted on purpose)
The error will go away if I use a new instance of the same db context. I noticed that when we get a DbConnection with the pre-built context the connection has no connection string but with the new instance it is set correctly.
I use the OnConfiguring to configure the provider as follow:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
if (_provider == Providers.SqlServer)
{
optionsBuilder.UseSqlServer(_connectionString);
}
else
{
throw new NotImplementedException("Provider not supported");
}
}
}
I put a breakpoint here and everytime the connection string is set to the same values. So I do not understand how one instance of the same context has an empty connection string.
Does anyone know the root cause of the issue?
Thank you,

So this happens because I was disposing a connection retrieved from context.Database.GetDbConnection(). I created polyfills for SqlQuery and ExecuteCommand which needed a connection string. So once one of them was called I will lose the current context's connection.

Related

Entity Framework Core - error: keyword not supported: '"server'

I am using Entity Framework Core 2.1. I scaffold my entity classes aka database first. When I try to get the data from one of the db tables, I get an error "keyword not supported for 'server'."
I googled and it looks like my connection string is not correct. Here it is setting in my json file
"DefaultConnection": "\"Server=myDb.com;Database=MyDb;user id=admin;Password=Password;MultipleActiveResultSets=true;Provider=System.Data.SqlClient"
I have seen other type of EF connection like
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
I am not sure about the .csdl, ssdl and msl.
Any help is appreciated. Thanks.
Error:
System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection()
at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value()
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable1 results, QueryContext queryContext, IList1 entityTrackingInfos, IList1 entityAccessors)+MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext()
Exception thrown: 'System.ArgumentException' in Microsoft.EntityFrameworkCore.dll
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.2\System.IO.MemoryMappedFiles.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The program '[3112] dotnet.exe' has exited with code -1 (0xffffffff).
Simple removing \" from front and end of connection string will work. In this case you can use complete connection string.
"DefaultConnection": "\"Server=tcp:myDb.com,1433;Initial Catalog=MyDb;Persist Security Info=False;User ID=admin;Password=Password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"\;"
to
"DefaultConnection": "Server=myDb.com,1433;Initial Catalog=MyDb;Persist Security Info=False;User ID=admin;Password=Password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
After playing with different connection string, here what I changed in my json to file to get it working
"DefaultConnection": "Server=myDb.com;Database=MyDb;user id=admin;Password=Password;
This is because the connection strings have been replaced after scaffolding the identity. The replacement string may look very similar but has some escaped characters in it.
I had appSettings.Development.json, appSettings.Staging.json and appSettings.Production.json, each with DIFFERENT connection strings.
After scaffolding my Identity using an EXISTING dbContext, it had replaced the connection string in appSettings.json files with the one single connection string. I have no idea why it picked that one but I realised the string was escaped so
"Server=MYCOMPNAME\\SQLEXPRESS;...
had become
"\"Server=KRYTEN\\\\SQLEXPRESS;
and this is why we get the error.

System.ArgumentException: An entry with the same key already exists. in sssi pack

I deploy the pack from ssis to SSISD, and try to create agent job to run the package.
after deploy to SSMS, getting the error
System.ArgumentException: An entry with the same key already exists.
===================================
An entry with the same key already exists. (System)
Program Location:
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.TreeSet1.AddIfNotPresent(T item)
at System.Collections.Generic.SortedDictionary2.Add(TKey key, TValue value)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollatedDictionaryCollection3.AddShadow(T obj)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollection3.Microsoft.SqlServer.Management.Sdk.Sfc.ISfcCollection.AddShadow(SfcInstance sfcInstance)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.CreateNewObjectFromRow(ISfcCollection childColl, IDataReader reader)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.InitObjectsFromEnumResultsRec(ISfcCollection childColl, IDataReader reader, Int32 columnIdx, Object[] parentRow)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.InitObjectsFromEnumResults(ISfcCollection childColl, IDataReader reader)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcInstance.InitChildLevel(ISfcCollection childColl)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollection3.InitializeChildCollection(Boolean refresh)
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollection3.EnsureCollectionInitialized()
at Microsoft.SqlServer.Management.Sdk.Sfc.SfcCollection3.Microsoft.SqlServer.Management.Sdk.Sfc.ISfcCollection.EnsureInitialized()
at Microsoft.SqlServer.Management.IntegrationServices.PackageInfo.get_Parameters()
at Microsoft.SqlServer.IntegrationServices.UITasks.ExecuteDataProvider.AddParametersDataGridToDataBus()
at Microsoft.SqlServer.IntegrationServices.UITasks.ExecuteDataProvider.AddToDataBus()
at Microsoft.SqlServer.IntegrationServices.UITasks.PropertiesDataProvider.Initialize(ITaskManager taskManager, IPropertyDictionary properties)
at Microsoft.SqlServer.Management.TaskForms.TaskManager.InitializeTaskFormComponent(Object component, ITaskFormComponentInfo info)
at Microsoft.SqlServer.Management.TaskForms.TaskFormManager.InitializeTaskFormComponent(Object component, ITaskFormComponentInfo info)
at Microsoft.SqlServer.Management.TaskForms.TaskManager.InitializeTaskFormComponents(IList1 taskFromComponentsInfo)
at Microsoft.SqlServer.Management.TaskForms.TaskFormManager.InitializeTaskFormComponents(IList1 taskFromComponentsInfo)
at Microsoft.SqlServer.Management.TaskForms.TaskManager.Initialize(String moniker, IContext context, IList1 taskFromComponents)
at Microsoft.SqlServer.Management.TaskForms.TaskFormManager.Initialize(String moniker, IContext context, ITaskFormInfo taskFormInfo)
at Microsoft.SqlServer.Management.TaskFormFactoryService.CreateTaskFormInstance(String taskFormMoniker, IContext context)
at Microsoft.SqlServer.Management.ActionHandlers.ShowTaskUIDialogActionHandler.RunTaskForm(IContext context)
at Microsoft.SqlServer.Management.ActionHandlers.DialogBasedActionHandler.RunTaskFormThread(Object contextObject)
Please help to fix it
This looks to be an error that one encounters when deploying SSIS packages having connection managers not in sync i.e. if a connection manager is changed as 'project connection manager' and this change is not reflected in the other packages using the same connection manager. Refer to the link for more details.
This issue has been occurred due to same connection name used for multiple packages.
Solution: Check which connections name are same for multiple packages .
Change the duplicate connection names and then Build and Deploy..
It worked for me :)

Why am I getting "Unable to load the specified metadata resource" error?

I have an MVC5 web application which I usually develop using my laptop.
I am trying to get the app running on my main machine at home for home-working days but have a problem connecting to the local dev database on SQL Server - when I start the app I get the following error:
More info 30/11/16:
Note that the model is generated from EDML using Entity Developer
Unable to load the specified metadata resource. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
The solution consists of 2 projects, one of which is an entity model project which is generated from EDMX.
Note: On my main machine (where it isn't working) the connection string in Web.config is the same as the machine where it works except for Data Source which refers to the SQL Server name on the main machine - I have checked this is correct several times:
I have read several Stack Overflow posts with similar issues - most point to something wrong with the path to the csdl, ssdl, msl part of the connection string.
I have:
Checked the server name is correct in the connection string
Checked the database name is correct in the connection string
Checked the database exists and is available
Checked each of the three files are where the connection string says they are (they are)
Tried using wildcard in the connection string: res://*/dllname.csdl|res://*/dllname.ssdl|res://*/dllname.msl
Update 30/11/2016:
From the suggestions in this link I have:
Checked the MetadataArtifactProcessing property - it is not set to Copy to Output directory
Checked the connection string
We don't have a post-compile task
From the suggestion in this link I have tried setting the connection string connectionString="metadata=res://*/;
Stack Trace:
[MetadataException: Unable to load the specified metadata resource.]
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.LoadResource() +85
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReader() +10
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderResource.CreateReaders(DataSpace spaceToGet) +72
System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderComposite.CreateReaders(DataSpace spaceToGet) +99
System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadEdmItemCollection(MetadataArtifactLoader loader) +41
System.Data.Entity.Core.Metadata.Edm.<>c__DisplayClass5.<GetMetadataWorkspace>b__0(String k) +37
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +72
System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace(String cacheKey, MetadataArtifactLoader artifactLoader) +75
System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace(DbConnectionOptions effectiveConnectionOptions) +126
System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace() +43
System.Data.Entity.Core.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection() +20
System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory) +393
System.Data.Entity.Core.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName) +35
App.Models.Entities..ctor() in C:\Users\Me\Desktop\App\App.MVC5\App.Entities.cs:37
App.MVC5.Models.CurrentUser..ctor(Boolean IsGuiDetailsRequired) in C:\Users\Me\Desktop\App\App.MVC5\Models\AccountModels.cs:87
App.MVC5.Controllers.HomeController..ctor() in C:\Users\Me\Desktop\App\App.MVC5\Controllers\HomeController.cs:11
[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) +114
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) +11
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'App.MVC5.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
Castle.Proxies.Invocations.IControllerFactory_CreateController.InvokeMethodOnTarget() +118
Castle.DynamicProxy.AbstractInvocation.Proceed() +80
Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +11
Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +41
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +25
Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +84
Castle.DynamicProxy.AbstractInvocation.Proceed() +108
Castle.Proxies.IControllerFactoryProxy.CreateController(RequestContext requestContext, String controllerName) +214
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
There's a very popular question over there and from its rating I can assume it helped a lot of people. It even mentions a blog post with complete troubleshooting for this problem. Also, this answer looks like something you didn't try yet.

MsDeploy with DbDacFx provider and Database reference

We are using DbDacFx provider to sync our production machine.
We have ssdt database project in our solution that we deploy along with our website.
The A.sqlproj has references to master.dacpac and another database project's dacpac, say X.dacpac.
All dacpacs are in same location for deployment.
When we try to deploy the A.dacpac we get errors as below:
Info: Deploying package to database: Faulted. Error: The reference to external elements from the source named 'X.dacpac' could not be resolved, because no such source is loaded. Error: The reference to external elements from the source named 'master.dacpac' could not be resolved, because no such source is loaded. .....above errors repeated multiple times..... An error occurred when the request was processed on the remote computer. Error: Exception has been thrown by the target of an invocation. ---> System.Exception: Member 'ClassName' was not found. at System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType) at System.Runtime.Serialization.SerializationInfo.GetString(String name) at System.Exception..ctor(SerializationInfo info, StreamingContext context) --- End of inner exception stack trace --- at System.RuntimeMethodHandle._SerializationInvoke(Object target, SignatureStruct& declaringTypeSig, SerializationInfo info, StreamingContext context) at System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context) at System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder) at System.Runtime.Serialization.ObjectManager.DoFixups() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, IMethodCallMessage methodCallMessage) at Microsoft.Web.Deployment.Base64EncodingHelper.DeserializeHelper(BinaryFormatter formatter, Byte[] buffer) at Microsoft.Web.Deployment.Base64EncodingHelper.Deserialize(String str, Exception& handledException) at Microsoft.Web.Deployment.SerializationHelper.Deserialize(String str) at Microsoft.Web.Deployment.SqlDacPacProvider.ProcessExeOutput() at Microsoft.Web.Deployment.SqlDacPacProvider.RunExecutableAsync(String exeName, String arguments, Int32 waitInterval, Int32 retryAttempts) at Microsoft.Web.Deployment.SqlDacPacProvider.Add(DeploymentObject source, Boolean whatIf) at Microsoft.Web.Deployment.DeploymentObject.Add(DeploymentObject source, DeploymentSyncContext syncContext) at Microsoft.Web.Deployment.DeploymentSyncContext.HandleAdd(DeploymentObject destObject, DeploymentObject sourceObject) at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildren(DeploymentObject dest, DeploymentObject source) at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenOrder(DeploymentObject dest, DeploymentObject source) at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject) at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable1 syncPassId) at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentAsyncData asyncData, Nullable1 passId) Error: Member 'ClassName' was not found. at System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType) at System.Runtime.Serialization.SerializationInfo.GetString(String name) at System.Exception..ctor(SerializationInfo info, StreamingContext context) Error count: 1.
Need to know how we can overcome the issues.
Thanks
Yatin.
Do the referenced dacpacs exist on the machine that is running the deploy?
If they do the easiest is to copy the dacpacs into the same folder as the dacpac you are deploying as the same directory will be checked, failing that the original path that contained the original dacpac.
This is still a pain.
We plan on scripting the sqlpackage.exe file command through runCommand provider and get automation going !!
Closing the question.
Thanks

Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'

In which situation following error occurs?
Unable to cast object of type 'MyType' to type 'Castle.Proxies.MyType'.
UPDATE:
I got this error message while binding MyType.FindAllByProperty("col1", "foo"); to a GridView (exactly a Telerik's one: RadGrid). This error is not occuring every time, just sometimes. Here is markup of my grid:
<telerik:RadGrid ID="grdList" runat="server" AutoGenerateColumns="false" OnNeedDataSource="grdList_NeedDataSource"
OnUpdateCommand="grdList_UpdateCommand" AllowAutomaticUpdates="True" OnItemUpdated="grdList_ItemUpdated"
AllowMultiRowEdit="true">
<MasterTableView EditMode="InPlace" DataKeyNames="PageInRole_id" AllowAutomaticUpdates="true">
<Columns>
<telerik:GridBoundColumn DataField="ContainerPage.PageTitle" HeaderText="Title" UniqueName="ContainerPage.PageTitle"
ReadOnly="true" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
UPDATE2
Here is all exception message and stack trace:
Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidCastException: Unable to cast object of type 'PineCMS.Core.PageInRole' to type 'Castle.Proxies.PageInRoleProxy'.]
Telerik.Web.UI.GetEnumerator>d__0.MoveNext() +175
Telerik.Web.UI.GridDataTableFromEnumerable.FillDataTableFromEnumerable(IQueryable enumerable) +1285
Telerik.Web.UI.GridDataTableFromEnumerable.FillData35() +3390
Telerik.Web.UI.GridDataTableFromEnumerable.FillData() +824
Telerik.Web.UI.GridResolveEnumerable.EnsureInitialized() +28
Telerik.Web.UI.GridEnumerableFromDataView..ctor(GridTableView owner, IEnumerable enumerable, Boolean CaseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +242
Telerik.Web.UI.GridDataSourceHelper.CreateGridEnumerable(GridTableView owner, IEnumerable enumerable, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +223
Telerik.Web.UI.GridDataSourceHelper.GetResolvedDataSource(GridTableView owner, Object dataSource, String dataMember, Boolean caseSensitive, Boolean autoGenerateColumns, GridColumnCollection presentColumns, String[] additionalField, Boolean retrieveAllFields) +595
Telerik.Web.UI.GridTableView.get_ResolvedDataSource() +243
Telerik.Web.UI.GridTableView.CreateChildControls(IEnumerable dataSource, Boolean useDataSource) +42
System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +72
System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +147
System.Web.UI.WebControls.DataBoundControl.PerformSelect() +261
Telerik.Web.UI.GridTableView.PerformSelect() +23
Telerik.Web.UI.GridTableView.DataBind() +363
Telerik.Web.UI.GridTableView.Rebind() +101
Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +1174
Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +185
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
Telerik.Web.UI.GridItem.OnBubbleEvent(Object source, EventArgs e) +142
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET Version:2.0.50727.4927
This exception probably comes from the code trying to re-attach a proxied/lazy-loading entity to a session. The most likely API call to throw this exception with a newer NHibernate (I don't have problem with 2.1 but I do have problems with latest) is Session.Lock(obj, LockMode.None).
If the programmer of this component first evicts the entity from the ISession and then re-loads it (perhaps cached?) into another one by id, or performs ISession.Update this problem should go away until the NHibernate team has figured out the underlying problem.
I had a similar problem with EntityFramework 6.0.
I had migrated from an old version of EntityFramework that did not use proxies and had some code that created and attached new instances of the entity via new MyEntity();.
My solution was to use dbContext.MyEntity.Create(); instead so I only work with proxies. Something similar should be available for NHibernate if I recall correctly.
My error was:
Unable to cast object of type 'MyProject.MyEntity' to type
'System.Data.Entity.DynamicProxies.MyEntity_849E94C98E5E543D6DF5245252144E3EAC00131F811886276B6ABD991719D232'
We ran into the same issue with RadGrid having AutomaticInserts. After inserting an item it throw InvalidCastException: Unable to cast object of type 'MyDbModel.Role' to type 'System.Data.Entity.DynamicProxies.Role_...' in DataBind() at Rebind().
The issue was gone after I adapted the DataBinding to have an OrderBy().

Resources