I have a simple MVC 5 test solution that is connected to a SQL server 2008 on the intranet here. I have followed this tutorial so far:
http://www.asp.net/mvc/overview/getting-started/database-first-development/generating-views
I can open the view, and it shows the listing but when I try to create a new one I get the following error:
{"Unable to update the EntitySet 'Movies' because it has a
DefiningQuery and no <InsertFunction> element exists in the
<ModificationFunctionMapping> element to support the current
operation."}
I used the Database first approach so I have no idea what has gone wrong. I understand that somehow he can't perform an Update. Is this something I need to fix inside the project or has it to do something with SQl server?
EDIT: here is the exception details
System.Data.Entity.Infrastructure.DbUpdateException was unhandled by user code
HResult=-2146233087
Message=Unable to update the EntitySet 'Movies' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at TestSite.Controllers.MoviesController.Create(Movy movy) in c:\Users\Rovc\Desktop\TestSite\TestSite\Controllers\MoviesController.cs:line 54
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
InnerException: System.Data.Entity.Core.UpdateException
HResult=-2146232032
Message=Unable to update the EntitySet 'Movies' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
Source=EntityFramework.SqlServer
StackTrace:
at System.Data.Entity.SqlServer.SqlGen.DmlSqlGenerator.ExpressionTranslator.Visit(DbScanExpression expression)
at System.Data.Entity.Core.Common.CommandTrees.DbScanExpression.Accept(DbExpressionVisitor visitor)
at System.Data.Entity.SqlServer.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree tree, SqlGenerator sqlGenerator, List`1& parameters, Boolean generateReturningSql, Boolean upperCaseKeywords, Boolean createParameters)
at System.Data.Entity.SqlServer.SqlGen.SqlGenerator.GenerateSql(DbCommandTree tree, SqlVersion sqlVersion, List`1& parameters, CommandType& commandType, HashSet`1& paramsToForceNonUnicode)
at System.Data.Entity.SqlServer.SqlProviderServices.CreateCommand(DbProviderManifest providerManifest, DbCommandTree commandTree)
at System.Data.Entity.SqlServer.SqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
at System.Data.Entity.Core.Common.DbProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(Dictionary`2 identifierValues)
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException:
I found the problem. The table that I was using was apparently missing a primary key. Once I designated the correct field as Primary everything worked.
Related
I'm having issues connecting a UWP device to MySQL after the latest Windows 10 update.
After doing research, it looks like there's no MySQL connector available that works with the new Windows update.
Everything worked fine before the update, but now I'm receiving this error:
{System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
at MySql.Data.MySqlClient.MySqlConnectAttrs.get_PID()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at MySql.Data.MySqlClient.NativeDriver.SetConnectAttrs()
at MySql.Data.MySqlClient.Authentication.MySqlAuthenticationPlugin.Authenticate(Boolean reset)
at MySql.Data.MySqlClient.NativeDriver.Authenticate(String authMethod, Boolean reset)
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlConnection.Open()
at SLBHandHeldFINAL.Config.Button_Click_1(Object sender, RoutedEventArgs e)}
Any help would be greatly appreciated!
Thanks in advance!
I am using EntityFramework to connect to a MySql server.
I have a method which inserts many objects in the database. For this, i am generating an SQL script, which i execute it using dbContext.Database.ExecuteSqlCommand(script) method.
This workflow works ok when the EntityFramework was connected to MS SQL Server.
Now, after i moved it to MySql, it throws error when executing the script.
Incorrect syntax near '`'.
Important
The script had been generated to match MySql syntax. If i run that script in MySQL Workbench, the query is executed successfully.
I think that EntityFramework is trying to parse the script i am sending, but in the MS SQL language.
Here is the exception Stack Trace:
at System.Data.SqlClient.SqlConnection.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.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__58()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__57()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at AppFormApp.Domain.EntityFramework.AppFormAppDatabaseService.<InsertAllObjectsAsync>d__1.MoveNext() in F:\GitRoot\AppFormApp\AppFormApp\AppFormApp.Domain\EntityFramework\AppFormAppDatabaseService.cs:line 120
UPDATE
This is the MySQL query generated
INSERT INTO `appformapp`.`appformdata`(`Id`, `ApplicationIdentifier`, `ApplicationName`, `LastSavedDate`, `LastActivity`)
VALUES (N'59bbf577-d601-4857-aabf-84b69b2d7b75', N'APP-TMH3EI', N'Test ABV', N'2016-10-17 05:56:16', N'2016-10-17 05:56:16');
The Entity Framework is already working with MySql. The error is only triggered when using dbContext.Database.ExecuteSqlCommand(script)
Hi I have this link sentence what am I doing wrong?
FYI. This is an error after debugging.
Dim categories = Aggregate pgmAccess In rvdDB.PgmAccesses
Where pgmAccess.OperatorID = RData.UserName
Join menuDef In rvdDB.MenuDefs On menuDef.ProgramName Equals pgmAccess.Program
Order By menuDef.MenuID
Select menuDef.ProgramDescription
Distinct Into ToList()
Error message
An exception of type 'System.NotSupportedException' occurred in
System.Data.Linq.dll but was not handled in user code
Additional information: Method 'System.Object
CompareObjectEqual(System.Object, System.Object, Boolean)' has no
supported translation to SQL.
__
Server Error in '/' Application.
Method 'System.Object CompareObjectEqual(System.Object, System.Object,
Boolean)' has no supported translation to SQL.
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.NotSupportedException: Method 'System.Object
CompareObjectEqual(System.Object, System.Object, Boolean)' has no
supported translation to SQL.
Source Error:
Line 16: Dim rvdDB As New RVDDataClassesDataContext Line 17:
Line 18: Dim categories = Aggregate pgmAccess In
rvdDB.PgmAccesses Where pgmAccess.OperatorID = RData.UserName Join
menuDef In rvdDB.MenuDefs On menuDef.ProgramName Equals
pgmAccess.Program Order By menuDef.MenuID Select
menuDef.ProgramDescription Distinct Into ToList() Line 19: Line 20:
categories.ForEach(AddressOf MakeButton)
Source File: C:\Users\pieterv\Documents\Visual Studio
2013\Projects\RVDMenu\RVDMenu\MenuFrm.aspx.vb Line: 18
Stack Trace:
[NotSupportedException: Method 'System.Object
CompareObjectEqual(System.Object, System.Object, Boolean)' has no
supported translation to SQL.]
System.Data.Linq.SqlClient.Visitor.VisitMethodCall(SqlMethodCall mc)
+576409 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +2146 System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression
exp) +8
System.Data.Linq.SqlClient.Visitor.VisitMethodCall(SqlMethodCall mc)
+115 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +2146 System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression
exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select) +46
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlVisitor.VisitAlias(SqlAlias a) +13
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +457
System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource source) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitJoin(SqlJoin join) +21
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +979
System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource source) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select) +27
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlVisitor.VisitAlias(SqlAlias a) +13
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +457
System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource source) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select) +27
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlVisitor.VisitAlias(SqlAlias a) +13
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +457
System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource source) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select) +27
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlVisitor.VisitAlias(SqlAlias a) +13
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +457
System.Data.Linq.SqlClient.SqlVisitor.VisitSource(SqlSource source) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect
select) +27
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlProvider.BuildQuery(ResultShape
resultShape, Type resultType, SqlNode node, ReadOnlyCollection1
parentParameters, SqlNodeAnnotations annotations) +588
System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query,
SqlNodeAnnotations annotations) +155
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression
query) +132
System.Data.Linq.DataQuery1.System.Collections.Generic.IEnumerable.GetEnumerator()
+35 System.Collections.Generic.List1..ctor(IEnumerable1 collection) +7675130 System.Linq.Enumerable.ToList(IEnumerable`1
source) +61 RVDMenu.MenuFrm.LoadCategories() in
C:\Users\pieterv\Documents\Visual Studio
2013\Projects\RVDMenu\RVDMenu\MenuFrm.aspx.vb:18
RVDMenu.MenuFrm.Page_Load(Object sender, EventArgs e) in
C:\Users\pieterv\Documents\Visual Studio
2013\Projects\RVDMenu\RVDMenu\MenuFrm.aspx.vb:12
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+627
From your error:
Method 'System.Object CompareObjectEqual(System.Object, System.Object, Boolean)' has no supported translation to SQL
This means that you are doing an object comparison that SQL does not know how to perform.
The places I see that you are doing this comparison are:
Where pgmAccess.OperatorID = RData.UserName
On menuDef.ProgramName Equals pgmAccess.Program
You need to check what the datatypes of those properties are. Remember that SQL only knows how to compare common datatypes, like strings, ints, doubles, etc. It does not know how to compare datatypes that you create.
I fixed the issue RData.Username had to have .tostring now it works. Thanks #Yuriy Galanter
I am getting this error in my recently deployed MVC 4 web application, whenever I click a link that requires database access:
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
When I run the mvc app locally, through visual studio, connecting to these remote databases, I do not get this error, and the credentials are correct because when I "Connect to database" it logs in and retrieves all the entities as normal. I published the site to the server's FTP, as the host does not have a webdeploy service.
Can anyone explain why my deployed app would have issues with the database and not my local version?
UPDATE
Before I exposed this NullReferenceException, it was a ReflectionTypeLoadException. Don't know if that means anything, but here:
[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) +0
System.Reflection.RuntimeModule.GetTypes() +4
System.Reflection.Assembly.GetTypes() +61
System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<.ctor>b_1(Assembly a) +11
System.Linq.d_142.MoveNext() +234
System.Collections.Generic.List1.InsertRange(Int32 index, IEnumerable1 collection) +392
System.Data.Entity.ModelConfiguration.Mappers.TypeMapper..ctor(MappingContext mappingContext) +258
System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model) +114
System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) +112
System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +59
System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) +123
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +461
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +52
System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +37
System.Linq.Queryable.Select(IQueryable1 source, Expression1 selector) +66
ProOptInteractive.Controllers.ServiceController.Index() +115
lambda_method(Closure , ControllerBase , Object[] ) +35
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +182
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c_DisplayClass2a.b_20() +24
System.Web.Mvc.Async.<>c_DisplayClass25.b_22(IAsyncResult asyncResult) +99
System.Web.Mvc.Async.WrappedAsyncResult1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
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() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Update
Ok I just attempted to deploy a brand new MVC app from Visual Studio, and that gave me no errors when trying to access models (I made a simple Students model and created a new "Student" in the database, something that would not work in my actual MVC app. Any ideas?
The table in the database might not exist. I am facing the same problem now, the easiest way is to delete the whole DB and let EF recreate everything. If you already have some sensitive data, then it is trickier. And you might try these too:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDbContext>());
// or you can use DropCreateDatabaseAlways<>
From here: EF4 Code First create new table
Or you can check this one: Entity Framework 4.1 Code First not creating tables
I am working with MySQL and the .Net EntityFramework 4 using the Code First approach. The mysql connector version is 6.4.3.
When I run the project for the first time my initializer attempts to "DropCreateDatabaseAlways". The database is created as well as all the tables. Then the following exception is thrown.
Column length too big for column 'ModelHash' (max = 21845); use BLOB or TEXT instead
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: MySql.Data.MySqlClient.MySqlException: Column length too big for column 'ModelHash' (max = 21845); use BLOB or TEXT instead
Source Error:
Line 38: public virtual List GetAll()
Line 39: {
Line 40: return dbSet.ToList();
Line 41: }
Line 42:
Source File: C:\Users\Andrew\Documents\Visual Studio 2010\Projects\SearchCore\OnlineID.DAL\GlobalGatewayRepository.cs Line: 40
Stack Trace:
[MySqlException (0x80004005): Column length too big for column 'ModelHash' (max = 21845); use BLOB or TEXT instead]
MySql.Data.MySqlClient.MySqlStream.ReadPacket() +198
MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId) +73
MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId) +20
MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force) +100
MySql.Data.MySqlClient.MySqlDataReader.NextResult() +836
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior) +1399
MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery() +36
MySql.Data.MySqlClient.MySqlScript.Execute() +551
MySql.Data.MySqlClient.MySqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +260
System.Data.Objects.ObjectContext.CreateDatabase() +84
System.Data.Entity.Internal.DatabaseOperations.CreateIfNotExists(ObjectContext objectContext) +28
System.Data.Entity.Database.CreateIfNotExists() +53
System.Data.Entity.DropCreateDatabaseAlways1.InitializeDatabase(TContext context) +233
System.Data.Entity.<>c__DisplayClass21.<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.RetryAction1.PerformAction(TInput input) +118
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +190
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +73
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +27
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +62
System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() +15
System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable.GetEnumerator() +40
System.Collections.Generic.List1..ctor(IEnumerable1 collection) +315
System.Linq.Enumerable.ToList(IEnumerable1 source) +58
OnlineID.DAL.GlobalGatewayRepository1.GetAll() in C:\Users\Andrew\Documents\Visual Studio 2010\Projects\SearchCore\OnlineID.DAL\GlobalGatewayRepository.cs:40
OnlineID.BAL.AccountService.GetAccounts() in C:\Users\Andrew\Documents\Visual Studio 2010\Projects\SearchCore\OnlineID.BAL\AccountService.cs:32
OnlineID.Website.Controllers.AccountManagement.AccountManagementController.Index() in C:\Users\Andrew\Documents\Visual Studio 2010\Projects\SearchCore\OnlineID.Website\Controllers\AccountManagement\AccountManagementController.cs:29
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.<>c_DisplayClass15.b_12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 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__DisplayClass81.b__7(IAsyncResult ) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c_DisplayClasse.b_d() +50
System.Web.Mvc.SecurityUtil.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() +8920029
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
I'm not sure what this "ModelHash" column is as it does not exist in my models.
Thanks,
AFrieze
I have identified the location of this ModelHash column, it is in the EdmMetadata table that is used to track changes. The error I am experiencing can be eliminated by adding the following modelBuilder.Conventions.Remove(); Is there a way to use EdmMetadata with MySQL then?
The IncludeMetadataConvention does nothing more than it maps the EdmMetadata entity.
void IConfigurationConvention.Apply(ModelConfiguration modelConfiguration)
{
modelConfiguration.Entity(typeof(EdmMetadata), false).ToTable("EdmMetadata");
}
AFAI see the framework just checks in other places if this class is mapped or not and acts accordingly.
As a workaround you could try to map the EdmMetadata entity in your mapping (instead of using this convention for that, so keep the convention removed), where you could explicitly map the ModelHash property with an appropriate size or type (text). On "how to map the field length or type of a field" you can find info here: How do I specify that a property should generate a TEXT column rather than an nvarchar(4000) According to the answers there this should change the type of the column to text:
modelBuilder.Entity<EdmMetadata>()
.Property(e => e.ModelHash)
.HasColumnType("text");
Can someone try this approach?