I'm working on my ASP.NET MVC 5 project
Here is my Admin code
[Authorize(Roles = "Admin")]
public ActionResult Admin()
{
return View(UserManager.Users);
}
All I want to do is to be able to delete users from database and its related records in AspNetUserRoles.
I added this into my web.config inside system.web section
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider"
connectionstringname="DefaultConnection" enablepasswordretrieval="false" enablePasswordReset="true"
requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider"
connectionStringName="DefaultConnection" applicationName="/" />
When trying to open the /Admin page it throws exception:
Invalid object name 'dbo.UsersInRoles'.
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.SqlClient.SqlException: Invalid object
name 'dbo.UsersInRoles'.
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:
[SqlException (0x80131904): Invalid object name 'dbo.UsersInRoles'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) +1789294 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
+5340642 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +61
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +377
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +137 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41 System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10 System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +66
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 executed) +138
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext) +475
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior) +239
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
+10 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +97
[EntityCommandExecutionException: An error occurred while executing
the command definition. See the inner exception for details.]
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +181
System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext
context, ObjectParameterCollection parameterValues) +1282
System.Data.Entity.Core.Objects.<>c__DisplayClass7.b__6()
+184 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +448 System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +270 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1
operation) +251
System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption) +645
System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +68 System.Data.Entity.Internal.LazyEnumerator1.MoveNext() +68 System.Linq.Buffer1..ctor(IEnumerable1 source) +216
System.Linq.Enumerable.ToArray(IEnumerable1 source) +77 System.Web.Providers.QueryHelper.GetRolesNamesForUser(MembershipContext ctx, String applicationName, String username) +8129 System.Web.Providers.DefaultRoleProvider.GetRolesForUser(String username) +219 System.Web.Security.RolePrincipal.IsInRole(String role) +9612755 System.Linq.Enumerable.Any(IEnumerable1 source,
Func2 predicate) +146 System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +333 System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +379 System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor)
+143 System.Web.Mvc.Async.<>c__DisplayClass21.b__19(AsyncCallback
asyncCallback, Object asyncState) +1680
System.Web.Mvc.Async.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback,
Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +94 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559 System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate1 beginDelegate,
EndInvokeVoidDelegate1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588 System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate1 beginDelegate,
EndInvokeVoidDelegate1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate1 beginDelegate,
EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag,
Int32 timeout, SynchronizationContext callbackSyncContext) +106
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) +446
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+301 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.34009
Where might I have gone wrong?
I think that your problem is due to the new Memebership infrastructure in MVC5.
On This link: http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2
I found the following tip which may help you:
If your app uses the User.IsInRole() method, add the following to the Web.config file.
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>
It appears you are very confused about authorization and authentication. As a quick and brief overview:
MVC 1-2 Used the default FormsAuthentication Framework. This required using the aspnet_regsql as Shai Aharoni mentioned in the comments.
MVC 3 was introduced with the SimpleMembership Provider Framework. This extended the default FormsAuthentication Model. Did not require aspnet_regsql but could be designed to be compatible with it.
MVC 4 was introduced with ASP.Net Identity 1.0. This completely removed the need for FormsAuthenication. Is not compatible with aspnet_regsql. This includes adding the following to the webconfig:
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
...
MVC 5 was released, and slightly later, ASP.Net Identity 2.0 was released. I'm pretty sure that Visual Studio 2013 with Update 1 or 2, now automatically uses ASP.Net Identity 2.0 (as they are forwards compatible 100%).
I added this into my web.config inside system.web section
What you've tried to do is add the now antiquated SimpleMembershipProvider and RoleProvider (Universal Providers) to ASP.Net Identity 1 or 2. This simply won't work out of the box, they are not compatible, they use different tables, different assemblies, etc.
If I load up the default MVC 5 template, which uses Identity 2.0 (with the TKey for User as string, just like 1.0), and a data source the looks like the following:
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication3-20140601125344.mdf;Initial Catalog=aspnet-WebApplication3-20140601125344;Integrated Security=True" />
The AuthrizeAttribute works, out-of-the-box with no changes made. They only way I can get the AuthorizeAttribute to not work, is if I add the AllowAnonymousAttribute at the controller level:
[AllowAnonymous]
public class HomeController
{
[Authorize]
public ActionResult Index()
{
return View();
}
}
The other possible but not probable problem is that you have Lazy Loading disabled on the ApplicationDbContext/IdentityDbContext AND are using an Identity version prior to 2.0-alpha1 as mentioned in a work item on codeplex.
Related
This question already has answers here:
INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server
(15 answers)
Closed 5 years ago.
I just want to know what is the meaning of this error? The INSERT statement conflicted with the FOREIGN KEY constraint "FK__thumbnail__instr__160F4887". The conflict occurred in database "MusicStoreDB", table "dbo.instrumentItem", column 'instrumentId'.
The statement has been terminated.
Here is the stack trace:
Server Error in '/' Application.
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__thumbnail__instr__160F4887". The conflict occurred in database
"MusicStoreDB", table "dbo.instrumentItem", column 'instrumentId'.
The statement has been terminated.
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.SqlClient.SqlException: The INSERT statement
conflicted with the FOREIGN KEY constraint "FK__thumbnail__instr__160F4887".
The conflict occurred in database "MusicStoreDB", table
"dbo.instrumentItem", column 'instrumentId'.
The statement has been terminated.
Source Error:
Line 74:
Line 75: obj.thumbnailImages.Add(subImg);
Line 76: obj.SaveChanges();
Line 77: }
Line 78: }
Source File: c:\Users\User1\Documents\Visual Studio
2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs Line: 76
Stack Trace:
[SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN
KEY constraint "FK__thumbnail__instr__160F4887". The conflict occurred in
database "MusicStoreDB", table "dbo.instrumentItem", column 'instrumentId'.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean
breakConnection, Action`1 wrapCloseInAction) +2434922
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception,
Boolean breakConnection, Action`1 wrapCloseInAction) +5736592
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning
(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean
asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet
bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +379
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream,
Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds, Boolean describeParameterEncryptionRequest) +2026
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method,
TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean
asyncWrite) +375
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
+53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior,
String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.
<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) +9
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1
.Dispatch(TTarget target, Func`3 operation, TInterceptionContext
interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher
.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
+355
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader
(CommandBehavior behavior) +167
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.
Execute(Dictionary`2 identifierValues, List`1 generatedValues) +234
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
+139
[UpdateException: An error occurred while updating the entries.
See the inner exception for details.]
System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
+319
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.
<Update>b__2(UpdateTranslator ut) +9
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(T
noChangesResult, Func`2 updateFunction) +120
System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() +77
System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
+11
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
options, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction) +163
System.Data.Entity.Core.Objects.<>c__DisplayClass2a.
<SaveChangesInternal>b__27() +22
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1
operation) +164
System.Data.Entity.Core.Objects.ObjectContext.
SaveChangesInternal(SaveOptions options, Boolean
executeInExistingTransaction) +222
System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
options) +7
System.Data.Entity.Internal.InternalContext.SaveChanges() +114
[DbUpdateException: An error occurred while updating the entries. See the
inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +199
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +27
System.Data.Entity.DbContext.SaveChanges() +20
ConnectionClassGuitarItems.AddThumnailImage(thumbnailImage subImg) in
c:\Users\User1\Documents\Visual Studio
2015\WebSites\MusicStore\App_Code\ConnectionClassGuitarItems.cs:76
Pages_CreateBrands.itemSaveButton_Click(Object sender, EventArgs e) in
c:\Users\User1\Documents\Visual Studio
2015\WebSites\MusicStore\Pages\CreateBrands.aspx.cs:231
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9696694
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
+204
System.Web.UI.WebControls.Button.System.Web.UI.
IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,
String eventArgument) +15
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint,
Boolean includeStagesAfterAsyncPoint) +1639
It means that you are trying to insert a row in instrumentItem table and the value that you are assigning to the instrumentId column, is invalid. There is a foreign key relationship between this table and another table in the database and the value of instrumentId should exist in the other table, but it doesn't.
I am new to programming so please bear me for asking a nob question
I have created a C# project in Visual Studio 2013, and it is working fine on localhost, I have used code first approach to create my database and used update-database in package manager console (and it was done successfully), tables are created on local server and there was no error on inserting values, but problem started to come when I tried to duplicate that database to my web server (I am using window hosting provided by [bigrock][1], I am mentioning the steps used by me to duplicate my local server database to my hosting server.
created SQL Server database on hosting panel(plesk panel).
copied connection string and added to web.config in Visual Studio, after save rebuilt the project.
Now downloaded the SQL Server 2012 Management Studio, and filled details about my server database in "Connect Object Explorer" section, tested connection and its showing me all the databases hosted at that server with my database.
opened package manager console in Visual Studio (on my local server) and used enable-migrations followed by update-migrations. And that is where I got the error Invalid column name 'xyz'.
next I checked my database in Management Studio, and there I can see all the tables created successfully with no column missing.
I ignored those errors at that time but when I tried to run my website and tried to register 1st user I got same errors with no idea where these are coming from
This is what I am getting on server (with whole stack trace):
Invalid column name 'RegisteredDate'.
Invalid column name 'Name'.
Invalid column name 'Mobile'.
Invalid column name 'Email'.
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.SqlClient.SqlException: Invalid column name 'RegisteredDate'.
Invalid column name 'Name'.
Invalid column name 'Mobile'.
Invalid column name 'Email'.
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:
[SqlException (0x80131904): Invalid column name 'RegisteredDate'.
Invalid column name 'Name'.
Invalid column name 'Mobile'.
Invalid column name 'Email'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +1789270
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5340622
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +275
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +208
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +163
WebMatrix.Data.Database.Execute(String commandText, Object[] args) +111
WebMatrix.WebData.DatabaseWrapper.Execute(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.CreateUserRow(IDatabase db, String userName, IDictionary2 values) +671
WebMatrix.WebData.SimpleMembershipProvider.CreateUserAndAccount(String userName, String password, Boolean requireConfirmation, IDictionary2 values) +65
WebMatrix.WebData.WebSecurity.CreateUserAndAccount(String userName, String password, Object propertyValues, Boolean requireConfirmationToken) +134
Riduk.Areas.Mobile.Controllers.AppStartController.Register(UserProfile model, String Password) +191
lambda_method(Closure , ControllerBase , Object[] ) +147
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +156
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +41
System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +31
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +54
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690164
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is what I am getting on using update-database in package-manager console
No pending explicit migrations.
Running Seed method.
System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'RegisteredDate'.
Invalid column name 'DOB'.
Invalid column name 'Email'.
Invalid column name 'Name'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
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, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at WebMatrix.Data.Database.Execute(String commandText, Object[] args)
at WebMatrix.WebData.DatabaseWrapper.Execute(String commandText, Object[] parameters)
at WebMatrix.WebData.SimpleMembershipProvider.CreateUserRow(IDatabase db, String userName, IDictionary2 values)
at WebMatrix.WebData.SimpleMembershipProvider.CreateUserAndAccount(String userName, String password, Boolean requireConfirmation, IDictionary2 values)
at WebMatrix.WebData.WebSecurity.CreateUserAndAccount(String userName, String password, Object propertyValues, Boolean requireConfirmationToken)
at MyProject.Migrations.Configuration.SeedMembership() in c:\Users\Me\Desktop\Project\MyProject\MyProject\Migrations\Configuration.cs:line 62
at MyProject.Migrations.Configuration.Seed(UsersContext context) in c:\Users\Me\Desktop\Project\MyProject\MyProject\Migrations\Configuration.cs:line 31
at System.Data.Entity.Migrations.DbMigrationsConfiguration1.OnSeed(DbContext context)
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:1f5ed896-956b-43dd-a08c-ff86b144021f
Error Number:207,State:1,Class:16
Invalid column name 'RegisteredDate'.
Invalid column name 'DOB'.
Invalid column name 'Email'.
Invalid column name 'Name'.
Here is my connection string from web.config:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=103.xx.xx.xx2;Integrated Security=False;User ID=MyDatabase;Password=MyPassWord;Connect Timeout=15;Encrypt=False;Packet Size=4096"
providerName="System.Data.SqlClient" />
</connectionStrings>
I hope this may be the sufficient for you guys to help a nob,
***Edit - deleted my models and schema for privacy concern
I am unable to solve my problem but I found a workaround while chatting with bigrock support person,I took following steps to resolve my problem :-
Connected SQL Management Server Studio with my local database.
followed steps given here i.e. right click on the desired database -> Click Tasks -> Click Back Up -> click ok and a ".bak" file will be created at location specified by you.(note- file name must be .bak otherwise it will give error)
open plesk panel -> click on Backup Manager -> Database backup Repository -> Add backup -> Upload .bak file that you have created in step 2 -> click ok (ignoring all warning)
done everything is working fine.
**Note- still looking for the cause of error in previous method
Update-Database command was giving this error:
There is already an object named 'StationsArrangeds' in the database.
So I deleted this table and now I'm getting this exception while trying to update database.
Using StartUp project 'MetroTrain'. Using NuGet project 'MetroTrain'.
Specify the '-Verbose' flag to view the SQL statements being applied
to the target database.
System.Data.Entity.Core.EntityCommandExecutionException: An error
occurred while executing the command definition. See the inner
exception for details.
System.Data.SqlClient.SqlException:
Invalid object name 'dbo.StationsArranged'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
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, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite)
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(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TInterceptionContext,TResult](Func1 operation, TInterceptionContext interceptionContext, Action1 executing, Action1 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
--- End of inner exception
Stack trace ---
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__a()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClassb.b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable.GetEnumerator>b__0()
at System.Lazy1.CreateValue()
at System.Lazy1.LazyInitValue()
at System.Lazy1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at MetroTrain.Models.StationsContext..ctor() in c:\Users\ghousia
pc\Dropbox\iMaq\MetroTrain\MetroTrain\Models\StationsContext.cs:line
22
--- End of stack trace from previous location where exception was thrown >
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type
contextType, DbProviderInfo modelProviderInfo, AppConfig config,
DbConnectionInfo connectionInfo)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration
configuration)
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String
targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action
command)
An error occurred while executing the command definition. See the inner exception for details.
I've gone through forums no solution found.
Manually deleting tables in code first causes EF to lose track of your model changes.
You can reset code first migrations by deleting migration history table and re-enable migration.
This is mostly because your database Migration table ("__MigrationHistory") is not sync with your Migration
you can change your Database Name in default connection string and create new database.
after create new database compare it with existing Database menualy and sync "__MigrationHistory" from new database to existing for later Migrate
I have one project use asp.net mvc 5 and the database use SQL Server 2008, when I deploy the application in IIS server A use windows 7 its normal and work, but when I deploy in IIS server B use windows server 2008 sp 1, the application not work. when I input values the error is
Server Error in '/SystemPurchase' Application.
Conversion failed when converting datetime from character string.
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.SqlClient.SqlException: Conversion failed when converting datetime from character string.
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:
[SqlException (0x80131904): Conversion failed when converting datetime from character string.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +388
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +688
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4403
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +82
System.Data.SqlClient.SqlDataReader.get_MetaData() +135
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6665229
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +6667096
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +577
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +107
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +288
System.Data.SqlClient.SqlCommand.ExecuteReader() +302
SystemPurchase.Models.transaction.insert() in c:\Users\Administrator.USer-PC.000\Documents\Visual Studio 2013\Projects\SystemPurchase\SystemPurchase\Models\transaction.cs:196
SystemPurchase.Controllers.NewEntryController.Index(HttpPostedFileBase filequo1, HttpPostedFileBase filetool1, HttpPostedFileBase filequo2, HttpPostedFileBase filetool2, HttpPostedFileBase filequo3, HttpPostedFileBase filetool3, HttpPostedFileBase filequo4, HttpPostedFileBase filetool4, HttpPostedFileBase filepo, HttpPostedFileBase filetool, FormCollection abc, transaction aa) in c:\Users\Administrator.USer-PC.000\Documents\Visual Studio 2013\Projects\SystemPurchase\SystemPurchase\Controllers\NewEntryController.cs:199
lambda_method(Closure , ControllerBase , Object[] ) +835
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +217
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c() +112
System.Web.Mvc.Async.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e() +452
System.Web.Mvc.Async.<>c__DisplayClass30.<BeginInvokeActionMethodWithFilters>b__2f(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass28.<BeginInvokeAction>b__19() +32
System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +231
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
I input a date from a model use
Datetime.Now.ToString("yyyy/MM/dd H:mm:ss tt")
in server A its work and no error, but in server B its error
any ideas to resolve it ?
I would suggest you use a specific FormatProvider, like below:
Datetime.Now.ToString("yyyy/MM/dd H:mm:ss tt", new CultureInfo("you culture Info"));
Here is a useful link, in which you will fund a list of all the available culture names.
You may use the TryParseExact
And choose the format that you need
For example :
DateTime OutputDate = null;
DateTime.TryParseExact(Datetime.Now.ToString(), "yyyy/MM/dd H:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
I have action in my controller which calls the following method :
public IQueryable<AaaUserContactInfo> getcontactinfo(long[] id)
{
var organizationsiteids = from accountsitemapping in entities.AccountSiteMappings
where id.Any(accountid => accountsitemapping.ACCOUNTID == accountid)
select accountsitemapping.SITEID;
var usersdepts = from userdept in entities.UserDepartments
join deptdefinition in entities.DepartmentDefinitions on userdept.DEPTID equals deptdefinition.DEPTID
where organizationsiteids.Any(accountid => deptdefinition.SITEID == accountid)
select userdept;
var contactsinfos = from userdept in usersdepts
join contactinfo in entities.AaaUserContactInfoes on userdept.USERID equals contactinfo.USER_ID
select contactinfo;
return contactsinfos;
}
But when I run the application and I navigate to the action method the folowing error will be raised on the view level:-
System.Data.EntityCommandExecutionException was unhandled by user code
HResult=-2146232004
Message=An error occurred while executing the command definition. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
at ASP._Page_Views_Home_CustomersDetails_cshtml.Execute() in c:\Users\Administrator\Desktop\new app DEMO2\MvcApplication4 - LATEST -\MvcApplication4\Views\Home\CustomersDetails.cshtml:line 6
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=15
LineNumber=105
Number=191
Procedure=""
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
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, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
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(CommandBehavior behavior)
at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
InnerException:
So what is causing this error??
UPDATED:-
LINQ, for most of its commands, employs deferred execution. It waits until you actually call for the data before it sends the query to that database. Here it looks like all of those queries are being deferred until later, when you try to grab something out of contactInfos.
I would try having it execute, like by throwing a .ToList() somewhere, to try and reduce the nesting that would be otherwise going on in the SQL.
EDIT: Since, per the comments, you appear to be getting the error on the first query, could you please try and having it say where id.Contains(accountsitemapping.ACCOUNTID)?
For future reference, you can log the generated SQL using:
var db = new DbContext();
db.Database.Log = Console.Write;
This will allow you to figure out which part is getting deeply nested. From there, you may have to re-write your query to load expensive calculations in a second step. Or consider writing it as a stored procedure.