ASP.NET MVC Problem with validation - asp.net-mvc

I have this simple controller:
public class OneController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(IList<TestModel> m)
{
return View(m);
}
}
And a very simple view with two objects of type TestModel, properly indexed.
When I submit the form with invalid data, I get the view with the errors highlighted.
However, when I re-submit it (without changing anything), I get this error:
[NullReferenceException: Object reference not set to an instance of an
object.]
System.Web.Mvc.DefaultModelBinder.UpdateCollection(ModelBindingContext
bindingContext, Type itemType) +612
System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext
bindingContext) +519
System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext
bindingContext) +829
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ParameterInfo
parameterInfo) +313
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(MethodInfo
methodInfo) +399
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
+232
System.Web.Mvc.Controller.ExecuteCore()
+152
System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +86
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +28
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase
httpContext) +332
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext
httpContext) +55
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext
httpContext) +28
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+358
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+64
Any idea on how can I debug this?

I was already looking at that article, and found the bug I was having (subtle, yet critical).
If you render the hidden field with the index using Html.Hidden, the helper will "accumulate" the previous values, so you'll end up with a hidden saying index=1, and the next saying index=1,2.
Changing the helper call to a manually coded hidden field fixed the issue.

Not sure I can answer without seeing more of the code and how your form is setup.
But, you could take a look at Phil Haack's blog entry about Model Binding To A List.Hope this helps.

Thanks that fixed it!
I replaced
<%= Html.Hidden("submitFormFields.index", controlID) %>
with
<input type="hidden" id="submitFormFields.index" name="submitFormFields.index" value="<%=controlID %>" />
Should we report this as a bug - It would be nice to have it fixed for ASP.Net MVC RC1

Related

A public action method 'undefined' was not found on controller '#######'

Maday,
i'm getting this error logged in db any idea or clue to fix this intermittent asp.net mvc exception.
thanks
Unhandled System.Web.HttpException (0x80004005): A public action method 'undefined' was not found on controller '#######'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I can't say for sure, but I suspect this is the result of a URL being constructed in JavaScript where a variable is not being defined.
Something like:
var action
var url = '/myContoller/' + action
This will result in a request to:
/myContoller/undefined
The intended URL could be for something that isn't even intended to be an MVC route. It could be for an image or something.
var imageUrl
var url = '/folder/' + imageUrl
/myFolder/undefined
MVC will try to route that, depending on how your routing is configured.
Is there any information in your logs about where the requests are coming from?
Update 1:
If you want MVC to ignore all requests to a particular area of your site (images directory for example), you can do something like this:
routes.IgnoreRoute("images/{*pathinfo}");
I have discerned a possible way to fix the image URL routing problem, based on #Dan's helpful answer:
So, because I have this "catch-all" route for 404 errors in my RouteConfig.cs:
// for 404-error page routing
routes.MapRoute(
name: "Error",
url: "{*url}",
defaults: new { controller = "Error", action = "PageNotFound" }
);
...MVC is oddly interpreting images that I have loaded via a Razor #foreach statement as URL's:
// this is triggering the weird problem, dunno why:
#foreach (string image in this.Model.ImageArray)
{
<img src="#this.Url.Content(image)" title="foobar" alt="#image" />
}
The Exception type is HttpException and the Exception message generated is:
A public action method '[object HTMLImageElement]' was not found on controller 'MyWebsite.Controllers.HomeController'
Placing routes.IgnoreRoute("MyImageFolderPath/{*pathinfo}"); at the top of the RegisterRoutes method in my RouteConfig.cs did not resolve this issue, but this did:
routes.IgnoreRoute("[object HTMLImageElement]");
It still seems hackish though, and due to my poor implementation of handling 404-errors...
You can verify that it works though by sprinkling breakpoints throughout your RouteConfig.cs, and also in the Application_Error method in Global.asax.cs (if you are also handling HttpException errors there).

A public action method 'cache' was not found on controller

I am getting A public action method 'cache' was not found on controller occasionally while executing the actionresult. Although here is no cache defined or used in my code.Don't know where from it is getting this. it is happening on telerik mvc grid's ajax binding. Here is the stack trace from elmah
HTTP Referrer
/mycontroller/75/myaction
Path Info
/mycontroller/cache/b19858cce4adf72d090c2334d5584f06
StackTrace
System.Web.HttpException (0x80004005): A public action method 'cache' was not found on controller 'myapp.Controllers.MyController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
There is a Chrome bug that matches this description: http://code.google.com/p/chromium/issues/detail?id=132059
According to the issue description it does not occur with other browsers so it is very likely that Chrome has to do something with it. However, the bug is not confirmed yet and there are multiple theories what might cause it. I would suggest that you test with multiple browsers yourself to check if it is related to Chrome.

Error in ASP.NET MVC Application

So we keep getting this error:
System.InvalidOperationException: The view 'Error' or its master was not found. The following locations were searched:
~/Views/Indications/Error.aspx
~/Views/Indications/Error.ascx
~/Views/Shared/Error.aspx
~/Views/Shared/Error.ascx
at System.Web.Mvc.ViewResult.FindView(ControllerContext context)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
when doing a multitude of things. It happens randomly, and sometimes happens doing the same exact thing that we just did without an error. Even when we catch an error in javascript sometimes, it still throws this error on the backend. Sometimes it navigates the user to a generic "Server Error" page as well.
What is a way we can handle this and display some information about the source of the issue? This stack isn't showing much...
Does your action method (or controller) has the [HandleError] attribute set on it? If that's the case and you don't have Error.aspx, then you will see this error. If you remove the [HandleError] attribute, you will be able to see the actual error.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My MVC app is returning SqlExceptions when trying to access any table in my database.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'.
My app us linq for the data layer.
If I use an old dll it works fine, (so doesn't seem to be a problem with the DB) just this latest app dll that I've uploaded.
details
[SqlException (0x80131904): Invalid object name 'dbo.Projects'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection) +1950890
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection) +4846875
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj) +194 System.Data.SqlClient.TdsParser.Run(RunBehavior
runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj) +2392
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +83
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +297
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async) +954
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) +12 System.Data.Common.DbCommand.ExecuteReader() +12
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query,
QueryInfo queryInfo, IObjectReaderFactory factory, Object[]
parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object
lastResult) +975
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query,
QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[]
userArguments, ICompiledSubQuery[] subQueries) +113
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression
query) +344
System.Data.Linq.DataQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
+35 System.Linq.Buffer1..ctor(IEnumerable1 source) +247 System.Linq.<GetEnumerator>d__0.MoveNext() +108
System.Linq.Buffer1..ctor(IEnumerable1 source) +259
System.Linq.<GetEnumerator>d__0.MoveNext() +108
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
+7665172 System.Linq.Enumerable.ToList(IEnumerable1 source) +61 Mezza_crm.Controllers.ProjectsController.GetProjectList(NameValueCollection form) in C:\mezza_crm\mezza_crm\Controllers\ProjectsController.cs:164
Mezza_crm.Controllers.ProjectsController.List() in
C:\mezza_crm\mezza_crm\Controllers\ProjectsController.cs:53
lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) +24
System.Web.Mvc.<>c__DisplayClassa.b__7()
+52 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func1 continuation) +254
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9()
+19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList1 filters, ActionDescriptor actionDescriptor,
IDictionary`2 parameters) +192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) +399
System.Web.Mvc.Controller.ExecuteCore() +126
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)
+151 System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57
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
Check the Initial Catalog parameter in your connection string. It may be that your code is looking in the wrong database for the Projects object.
For example, if you have database syncing setup in such a way that only a subset of the master-database's tables are transferred, you can encounter this error if Linq to SQL is expecting all tables to be in the database pointed to by the connection string.
I have seen that the new versions when you define the resulting entities better define them in the following way if you handle a different scheme, I had a similar problem
You must add System.ComponentModel.DataAnnotations.Schema
using System.ComponentModel.DataAnnotations.Schema;
[Table("InstitucionesMilitares", Schema = "configuracion")]
Do you have access to the SQL Server you are querying?
Can you see a Table or View called dbo.Projects there?
If not, that would be a good place to look.
Linq to SQL creates an object map between the database and the application. If your new DLL that you're deploying doesn't match with the database anymore, then this is the sort of error you'd expect to get.
Do you perhaps have different database schemas between your development environment and the deployment environment?
This maybe due to an incorrect table name from where you are fetching the data. Please verify the name of the table you mentioned in asmx file and the table created in database.
Delete _MigrationHistory table in (yourdatabseName > Tables > System Tables) if you already have in your database and then run below command in package manager console
PM> update-database
TLDR: Check that you don't connect to the same table/view twice.
FooConfiguration.cs
builder.ToTable("Profiles", "dbo");
...
BarConfiguration.cs
builder.ToTable("profiles", "dbo");
For me the issue was that I was trying to add an entity that connected to the same table as some other entity that already existed.
I added a new DbSet with entity and config, thinking we don't have it in our solution yet, however after searching for table name through all solution I found another place where we already connected to it.
Switching to use existing DbSet and removing my newly added one solved the issue.
The cause of this problem could be a property setting of the database (Sql2008R2 with .NET4).
Problem is reproducible at will when changing the COLLATION value of a database.
To display COLLLATION, use the Sql Server Mgmt Studio.
Right-click the database and select Properties -> General, Then look under Maintenance for the COLLATION value
To change COLLATION, (still) use the Sql Server Mgmt Studio.
Right-click the database and select Properties -> Options, From there, you can change the COLLATION value
If you are in that phase of development where you have an method inside your context class that creates testdata for you, don't call it in your constructor, it will try to create those test records while you don't have tables yet. Just sharing my mistake...
Try to do this way
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
or if you use .net core try it
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Usuario>().ToTable("Usuario");
}
Replace Usuario for your Entity Name, like a DbSet<<EntityName>> Entities without Plural
If you use two databases you can add another DataClasses.dbml and map the second database into it.
It works.
I had the same error. The cause was that I had created a table with wrong schema(it ought to be [dbo]). I did the following steps:
I dropped all tables which does not have a prefix "dbo."
I created and run this query:
CREATE TABLE dbo.Cars(IDCar int PRIMARY KEY NOT NULL,Name varchar(25) NOT NULL,
CarDescription text NULL)
GO
The problem I had was because I had made a database in my LocalDb.
If that's the case then you have to write is as shown below:
"SELECT * FROM <DatabaseName>.[dbo].[Projects]"
Replace with your database name.
You can probably also drop the "[ ]"
I have tried almost all the answers from below list, but did not work for me. But read the exception well and then tried rename my Dbset name TransactionsModel to Transactions
and it work for me.
old Code:
public class MyContext : DbContext
{
//....
public DbSet<Models.TransactionsModel> TransactionsModel { get; set; }
}
New Code:
public class MyContext : DbContext
{
//....
public DbSet<Models.TransactionsModel> Transactions { get; set; }
}

ASP.NET-MVC (IIS6) Error on high traffic: Specified cast is not valid

I just launched my tiny webapp on my humble dedicated server (Win2003)... running ASP.NET MVC, LINQ2SQL, SQL Express 2005, and IIS6 (setup with wildcard mapping)
The website runs smoothly 90% of the times. However, on relatively high traffic, LINQ2SQL throws the error:
Specified cast is not valid
This error is ONLY thrown at high traffic. I have NO IDEA how or exactly why this happens. Caching did not remove this problem entirely.
Anyone seen this problem before? are there any secret SQL Server tweaking I should've done?
Or at least, any ideas on how to diagnose this issue? because i'm out!
Naimi
Stacktrace (from Event Log):
at System.Data.SqlClient.SqlBuffer.get_SqlGuid()
at System.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
at Read_Friend(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at Dudlers.Web.Models.DudlersDataContext.GetFriendRequests(Guid userId) in C:\Web\Models\DudlersDataContext.cs:line 562
at Dudlers.Web.Controllers.BaseController.View(String viewName, String masterName, Object viewData) in C:\Web\Controllers\BaseController.cs:line 39
at System.Web.Mvc.Controller.View(String viewName)
at Dudlers.Web.Controllers.CatController.Index() in C:\Web\Controllers\CatController.cs:line 25
at lambda_method(ExecutionScope , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(MethodInfo methodInfo, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.b__8()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.c__DisplayClassb.c__DisplayClassd.b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(MethodInfo methodInfo, IDictionary`2 parameters, IList`1 filters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
We had a similar problem with LINQ that we get "Unable to cast object of type 'System.Int32' to type 'System.String'" and "Specified cast is not valid."
Examples of stacktraces
System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.
at System.Data.SqlClient.SqlBuffer.get_String()
at System.Data.SqlClient.SqlDataReader.GetString(Int32 i)
at Read_Person(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RF.Ias.Services.Person.BusinessLogic.PersonTransactionScripts.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)
at CompositionAopProxy_5b0727341ad64f29b816c1b73d11dd44.GetPersons(IEnumerable`1 personIds, Boolean includeAddress, Boolean includeContact)
at RF.Ias.Services.Person.ServiceImplementation.PersonService.GetPersons(GetPersonRequest request)
System.InvalidCastException: Specified cast is not valid.
at System.Data.SqlClient.SqlBuffer.get_Int32()
at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)
at Read_GetRolesForOrganisationResult(ObjectMaterializer`1 )
at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at RF.Ias.Services.Role.DataAccess.RoleDataAccess.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at RF.Ias.Services.Role.BusinessLogic.RoleTransactionScripts.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at CompositionAopProxy_4bd29c6074f54d10a2c09bd4ab27ca66.GetRolesForOrganisation(GetRolesForOrganisationCriteria criteria, Int32 pageIndex, Int32 pageSize, Int32& recordCount)
at RF.Ias.Services.Role.ServiceImplementation.RoleService.GetRolesForOrganisation(GetRolesForOrganisationRequest request)
We used to get these exceptions if we first got a exception like this "System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first." or " A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)".
The first exception occur for a different instance of the DataCOntext then for all those that then are following.
After some research and asking in this thread , I found that the reason was that I did not dispose the DataContexts. After I started to do that, it dissappered.
Sounds like maybe a race condition, or perhaps a rare bug that is only correlated with high traffic because that when most of your requests occur.

Resources