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; }
}
Related
We're running a web application distributed across load balanced 3 web servers. The exact same code base & configuration is deployed across the 3 servers, and since about 1 hour ago I'm getting the following error on one of them, but not the other two.
System.InvalidOperationException: An error occurred when trying to create a controller of type 'XXX.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor. ---> System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
--- End of inner exception stack trace ---
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
We are running this with ASP.NET MVC (with Output Caching), NHibernate (with NHibernate caching) & StructureMap. The cache is not shared, so each web server manages its own cache, though the cache dependencies are the same across the 3 servers.
I don't really know where to start describing what/where it could be going wrong or the circumstances, because it's so strange to me.
I've seen this once before about 2 weeks ago, but it went away on its own after about an hour and I haven't seen it since. Has anyone else seen an error like this before?
Well, it seems your HomeController is missing a parameterless constructor. Are you sure it has one?
The default controller factory needs one to intialize your constructor.
Unless you are using your own ControllerFactory, in which case you need to register it during Application_Start:
protected void Application_Start()
{
//other code
ControllerBuilder.Current.SetControllerFactory(new MyCustomControllerFactory());
}
Assuming you're resolving controllers with structuremap, it may be your components are registered at the wrong place/time.
Are you registering components in Application_Start ?
I'm using ASP.NET MVC 3 and have learnt through the MVC Music Store and other sources. I was able to create a database and have it live but the weird thing was about 5 hours after it was live it went down and had the following error and stack trace:
Note: This also seems to be the case whenever I publish the site. I have to go and delete the database manually for it to re create it and then it will work. But now that I'm live I can't do that because data is already being stored in there that I don't want to redo.
File already exists. Try using a different database name. [ File name = C:\HostingSpaces\...\wwwroot\App_Data\Test.sdf ]
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.Data.SqlServerCe.SqlCeException: File already exists. Try using a different database name. [ File name = C:\HostingSpaces\mtnp55\pricexperience.com\wwwroot\App_Data\Test.sdf ]
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:
[SqlCeException (0x80004005): File already exists. Try using a different database name. [ File name = C:\HostingSpaces\...\wwwroot\App_Data\Test.sdf ]]
System.Data.SqlServerCe.SqlCeEngine.ProcessResults(IntPtr pError, Int32 hr) +72
System.Data.SqlServerCe.SqlCeEngine.CreateDatabase() +658
System.Data.SqlServerCe.SqlCeProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 timeOut, StoreItemCollection storeItemCollection) +194
System.Data.Objects.ObjectContext.CreateDatabase() +84
System.Data.Entity.Internal.DatabaseOperations.Create(ObjectContext objectContext) +8
System.Data.Entity.Database.Create() +76
System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context) +387
System.Data.Entity.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c) +75
System.Data.Entity.Internal.<>c__DisplayClass5.<PerformDatabaseInitialization>b__3() +19
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +72
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +169
System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c) +7
System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input) +118
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action) +190
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +73
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +28
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +62
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +37
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
PriceXperience.Controllers.AppsController.ViewLeaderboards(Int32 gameId) in C:\Users\Public\Documents\Development\...\Controllers\AppsController.cs:42
lambda_method(Closure , ControllerBase , Object[] ) +101
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.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() +8841105
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
I've tried many things but still cannot figure out why it does this. I do have a database initialize.
System.Data.Entity.Database.SetInitializer<MobileEntities>(new SampleData());
public class SampleData : CreateDatabaseIfNotExists<MobileEntities>
The code that runs when I try to access the db is the following:
public ActionResult ViewLeaderboards(int gameId)
{
var leaderboards = from u in mobileDB.Scores
where u.GameId == gameId
select u;
return View(leaderboards.OrderByDescending(u => u.Score).ToList());
}
When publishing you need to be sure to REMOVE the Initializer from the Global.asax. The Initializer is only for populating test data, and should not be in use during production. I also remember reading somewhere that setting the Initializer to null might work.
Database.SetInitializer<MyContext>(null);
Or just comment out the line where you call SetInitializer before publishing. I also exclude my Initializer class from the project before publishing.
The default strategy for Code First contexts is an instance of CreateDatabaseIfNotExists.
So it is necessary to include the
Database.SetInitializer<MyContext>(null);
so that the default initializer is not called which might then give an error!
Also, it is necessary to include the generic tag when setting it to null or the compiler will give an error.
So basically, I developed this ASP.Net MVC application on a Windows 7 box with Visual Studio 2008. It works well on the local machine, and I was able to host it in IIS no worries. I then decided to upload it onto subversion, and fetch it on a different Windows Server 2008 machine. I downloaded it, had the IIS document root point to my application folder, and started it up.
I can visit the site fine. However, as soon as it needs to do anything with the SQL database I get the following error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
My ConnectionString to the SQL database is as follows:
<add name="UserClaimsConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\UserClaims.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
The error throws a wobble about allowing remote connections, but the database is local! Additionally, when I look at the StackTrace of the error, I see something odd at one portion:
OpenIdProviderMvc.Models.ClaimRepository.ResetAutoSend(String upi) in C:\OpenIdProviderMvc\Models\ClaimRepository.cs:40
The directory which it is referring to happens to be where I had it stored... on the development box! It is stored in a different location on the Windows 2008 server.
Where have I gone wrong in migrating this project?
EDIT:
Here is the full stack trace to provide a bit of additional information.
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4846887
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject) +4860189
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +90
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +376
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +221
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +189
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +4861315
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +31
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +433
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +499
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) +44
System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe() +45
System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode() +20
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +57
System.Data.Linq.DataQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +35
OpenIdProviderMvc.Models.ClaimRepository.ResetAutoSend(String upi) in C:\Downloads\DotNetOpenAuth-3.3.1.9337\OpenIdProviderMvc\Models\ClaimRepository.cs:40
OpenIdProviderMvc.Controllers.AccountController.LogOn(String userName, String password, String returnUrl, Boolean resetAttributeRelease) in C:\Downloads\DotNetOpenAuth-3.3.1.9337\OpenIdProviderMvc\Controllers\AccountController.cs:66
lambda_method(ExecutionScope , ControllerBase , Object[] ) +245
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.<InvokeActionMethodWithFilters>b__7() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
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
The path in the stack trace probably points to some path on your dev machine because that is what is in the .pdb files (have they been added to subversion?). I don't think this is related to the connection error and you will probably have to sort that out separately.
You need to install SQL Server 2008 Express on the server if it is not already installed. ASP.NET needs sql server express installed to attach the mdf database file in your data directory.
You can download it here
I'm having some trouble getting the code to work from the book "Pro ASP.NET MVC Framework." I'm on page 96 for those that may have worked through this book before. When I run the code I get the following:
System.Data.SqlClient.SqlException was unhandled by user code
Message="Invalid object name 'Products'."
Source=".Net SqlClient Data Provider"
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=208
Procedure=""
Server=".\\SQLEXPRESSADV"
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.Table`1.GetEnumerator()
at System.Data.Linq.Table`1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at WebUI.Controllers.ProductsController.List() in C:\Documents and Settings\adamsb1\My Documents\Visual Studio 2008\Projects\StoreSolution\WebUI\Controllers\ProductsController.cs:line 28
at lambda_method(ExecutionScope , 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__DisplayClassa.<InvokeActionMethodWithFilters>b__7()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
All my code builds fine with no errors and it appears to be identical to the book. However, I can't get this to work. I'm an old school asp guy so this is all new to me.
The error is in the database. Either the connection string you have provided points to the wrong database, or the database you are using is missing the table "Products", which is expected to be there.
Since it looks like you are using an SQLExpress database, I might guess that you haven't setup the tutorials database - the program is trying to read from whatever SQLExpress database you already have setup on your machine.
Problem solved!
David you pointed me in the right direction...thanks!
I swapped out the following on my connection string:
OLD:
Server=.\SQLEXPRESSADV.SportsStore;Trusted_Connection=yes;"
For the one below and it works now.
NEW:
Data Source=.\SQLEXPRESSADV;Initial Catalog=SportsStore;Integrated Security=True;Pooling=False
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.