Using CodeFirst.DontDropDbJustCreateTablesIfModelChanged causes attachment issues to the ObjectStateManager in EF 4.3 - entity-framework

[EDIT]: The application works fine in my local but won't run in AppHarbor. At the initial load of my site, I'd get this error mentioned in another question, if I reload the page then I'd get the error mentioned below. As mentioned by appharbor's Admin, they are working on the problem with new relic and ninject. But I'm not quite sure if my 2nd error is still related with appharbor's issue with new relic. Does Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged work properly with EF 4.3? Do I just wait on their update?
[InvalidOperationException: The object cannot be detached because it is not attached to the ObjectStateManager.]
at System.Data.Objects.ObjectContext.Detach(Object entity, EntitySet expectedEntitySet)
at System.Data.Objects.ObjectContext.Detach(Object entity)
at Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged`1.SaveModelHashToDatabase(T context, String modelHash, ObjectContext objectContext)
at Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged`1.InitializeDatabase(T context)
at System.Data.Entity.Database.<>c__DisplayClass2`1.<SetInitializerInternal>b__0(DbContext c)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClass8.<PerformDatabaseInitialization>b__6()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
at Core.Repository`2.Find(Expression`1 predicate) in d:\temp\2otuf0q2.xtn\input\Domain\Core\Repository.cs:line 52
at Data.RegistrantRepository.GetAllRegistrant() in d:\temp\2otuf0q2.xtn\input\Data\Data\RegistrantRepository.cs:line 20
at IPOD.Controllers.HomeController.Index() in d:\temp\2otuf0q2.xtn\input\IPOD\Controllers\HomeController.cs:line 28
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.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

For me it looks like the initializer is trying to update the EdmMetadata table - at least this is what I infere from:
Devtalk.EF.CodeFirst.DontDropDbJustCreateTablesIfModelChanged`1.SaveModelHashToDatabase(T context, String modelHash, ObjectContext objectContext)
In EF 4.3 the EdmMeatadata table will not be created (it will be used though if you have one in your database and model did not change - i.e. when you upgrade from 4.1/4.2 to 4.3+ - for more details see: http://blog.oneunicorn.com/2012/01/13/ef-4-3-beta-1-what-happened-to-that-edmmetadata-table/)
In 4.3 world you want to use migrations if your model changes and you need to update the database but don't want to actually delete and recreate it. Take a look at this walkthorugh: http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx

Related

"The given key was not present in the dictionary." when adding Association to Entities

Using EF6 / VS 2013, I have created an ADO.NET Entity Data Model. This model uses three views, stored in SQL Server, to prepare the data in a suitable form from an existing system. One for Users (vw_Users), one for Roles (vw_Roles) and a cross-reference/association view (vw_UserRoles).
When the User and Role entities are mapped, the application compiles and executes without issue. However, when I add the Association between User and Role and map it to the vw_UserRoles view, I get an EntityCommandCompilationException with an inner exception, KeyNotFoundException {"The given key was not present in the dictionary."}.
An exception of type 'System.Data.Entity.Core.EntityCommandCompilationException' occurred in mscorlib.dll but was not handled in user code
Additional information: An error occurred while preparing the command definition. See the inner exception for details.
To me it just feels like a bug but I am new to a lot of the EF and it could be to do with connecting to views. Out of interest I implemented this trick to treat the view as a table but it made no difference.
UPDATE #1: I created a new web application with a new SQL Server database. I created the underlying tables with relationships and a view for each table. When I create a entity model based on the tables, I have no problems -- even with the association. When I created a model from the views, I get the KeyNotFoundException. Note: I have corrected the keys and added and mapped the association on the second, view-based model. You can download the project from here - http://sdrv.ms/1eZ7ytp
UPDATE #2: I have logged this as an issue with MS # Codeplex - https://entityframework.codeplex.com/workitem/1777
I'm still stumped on this one and am really keen to complete this using a series of views. Any thoughts? Please....?
Full Exception:
System.Data.Entity.Core.EntityCommandCompilationException was unhandled by user code
HResult=-2146232005
Message=An error occurred while preparing the command definition. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver)
at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
at System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(WrappedEntityKey key, String keyValuesParamName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues)
at System.Data.Entity.DbSet`1.Find(Object[] keyValues)
at Mind.Mindlink.Portal.Controllers.HomeController.Index() in c:\Users\James\Documents\Visual Studio 2013\Projects\Mind.Mindlink.Portal\Mind.Mindlink.Portal\Controllers\HomeController.cs:line 13
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__36(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__3c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
InnerException: System.Collections.Generic.KeyNotFoundException
HResult=-2146232969
Message=The given key was not present in the dictionary.
Source=mscorlib
StackTrace:
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Data.Entity.Core.Mapping.ViewGeneration.Structures.MemberDomainMap.GetDomainInternal(MemberPath path)
at System.Data.Entity.Core.Mapping.ViewGeneration.Structures.MemberDomainMap.GetDomain(MemberPath path)
at System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateIsOfTypeCondition(MemberPath currentPath, IEnumerable`1 derivedTypes, MemberDomainMap domainMap)
at System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateAssociationConstraints(EntitySetBase extent, MemberDomainMap domainMap, EdmItemCollection edmItemCollection)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewgenContext..ctor(ViewTarget viewTarget, EntitySetBase extent, IList`1 extentCells, CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap, MemberDomainMap updateDomainMap, StorageEntityContainerMapping entityContainerMapping)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.CreateViewgenContext(EntitySetBase extent, ViewTarget viewTarget, CqlIdentifiers identifiers)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateDirectionalViewsForExtent(ViewTarget viewTarget, EntitySetBase extent, CqlIdentifiers identifiers, KeyToListMap`2 views)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateDirectionalViews(ViewTarget viewTarget, CqlIdentifiers identifiers, KeyToListMap`2 views)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateAllBidirectionalViews(KeyToListMap`2 views, CqlIdentifiers identifiers)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewgenGatekeeper.GenerateViewsFromCells(List`1 cells, ConfigViewGenerator config, CqlIdentifiers identifiers, StorageEntityContainerMapping containerMapping)
at System.Data.Entity.Core.Mapping.ViewGeneration.ViewgenGatekeeper.GenerateViewsFromMapping(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(StorageEntityContainerMapping entityContainerMap, Dictionary`2 resultDictionary)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer container)
at System.Data.Entity.Core.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection)
at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace)
at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase extent)
at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ExpandView(ScanTableOp scanTableOp, IsOfOp& typeFilter)
at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode, ScanTableOp scanTableOp, IsOfOp& typeFilter)
at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.ScanTableOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)
at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(FilterOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.FilterOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitSortOp(SortBaseOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.Visit(ConstrainedSortOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.ConstrainedSortOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitPhysicalOpDefault(PhysicalOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.Visit(PhysicalProjectOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.PhysicalProjectOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(Dictionary`2& tvfResultKeys)
at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState, StructuredTypeInfo& typeInfo, Dictionary`2& tvfResultKeys)
at System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets)
at System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(DbCommandTree ctree, List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
InnerException:
I have the same issue. When the model was originally created the EF version used was 5. Now using VS 2012 and EF6. Don't want to roll back to EF5.
UPDATE: Identified as a regression as part of the initial EF6 release.
Thanks for reviewing the project for me, #Pawel. If you can put a comment on the CodePlex issue, that would likely aid in it getting some priority. http://entityframework.codeplex.com/workitem/1777
On one hand I am happy the issue is repeatable and a likely bug. On the other hand, I just want to get on with doing this in EF 6. I have resorted to completing this in VS 2012 using EF 5 for the meantime. I will update if I uncover anything else.

Inserting Spatial\Geometry in EF5 with dotConnect 6.7 for PostgreSQL

I installed the latest dotConnect for PostgreSQL. Im trying to insert a record in the Postgres DB. I have a geometry column what gives me errors. Here is the code:
using (var context = new WKP_DBEntities())
{
var Location = DbGeometry.PointFromText(string.Format("POINT({0} {1})", 157873, 364282), 28992);
var record = new monitoring_object()
{
geometry = Location,
last_changed_by = "ssg",
};
context.monitoring_object.Add(record);
context.SaveChanges();
}
Here is the error message:
System.Data.Entity.Infrastructure.DbUpdateException was unhandled
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at ConsoleApplicationGEOdata.Program.Main(String[] args) in c:\Users\Stefan\Documents\Visual Studio 2012\Projects\ConsoleApplicationGEOdata\ConsoleApplicationGEOdata\Program.cs:line 38
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.ArgumentException
HResult=-2147024809
Message=Cannot convert value
Source=Devart.Data.PostgreSql
StackTrace:
at Devart.Data.PostgreSql.af.a(Object A_0, Type A_1, Encoding A_2)
at Devart.Data.PostgreSql.af.a(String A_0, Encoding A_1, PgSqlType A_2, Object A_3, Int32 A_4, Boolean A_5)
at Devart.Data.PostgreSql.PgSqlCommand.a(String A_0, Encoding A_1, ArrayList A_2, Boolean A_3)
at Devart.Data.PostgreSql.PgSqlCommand.InternalExecute(CommandBehavior behavior, IDisposable stmt, Int32 startRecord, Int32 maxRecords)
at Devart.Common.DbCommandBase.InternalExecute(CommandBehavior behavior, IDisposable stmt, Int32 startRecord, Int32 maxRecords, Boolean nonQuery)
at Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior behavior, Boolean nonQuery)
at Devart.Common.DbCommandBase.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at Devart.Data.PostgreSql.Entity.y.a(CommandBehavior A_0)
at Devart.Common.Entity.i.b(CommandBehavior A_0)
at Devart.Data.PostgreSql.Entity.y.b(CommandBehavior A_0)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException:
What am I doing wrong?
Your code works in our environment:
a) dotConnect for PostgreSQL v 6.7.287
b) SharpMap v1 RC3
c) Postgis 2.0
d) DDL:
CREATE TABLE monitoring_object
(
id serial NOT NULL,
geometry geometry,
last_changed_by character varying
);
Please give us the following information:
1) the version of your SharpMap. Be aware that current release of dotConnect for PostgreSQL supports SharpMap 1.0 RC3 ( http://sharpmap.codeplex.com/releases/view/106717 ). The 1.0 Final version will be supported soon
2) the version of your Postgis. It should be of the 2.0 (or higher) version. You can check it by executing "select postgis_version()" in the database
3) the DDL script of your monitoring_object table
4) if possible send us a small test project
The corresponding Devart documentation is available at http://blogs.devart.com/dotconnect/enhanced-entity-framework-spatials-support-for-oracle-mysql-and-postgresql.html .

Model-First with Existing DB. New DB always attempts to be created. Results in 'CREATE TABLE permission denied in database'

I created a model-first diagram pointing to a couple of views on an existing DB. When I attempt to query said DB, EF attempts to create & update said DB (despite being told not to).
As with many existing DBs one wants to query, I have SELECT permissions, but not DB create permissions. I don't want EF mucking with creating ANY objects for this particular DB (MyDb)
There are a couple of strange things:
1. The model shouldn't need to update the DB (it matches the view)
2. Database.SetInitializer(null) //Set on MVC Application_Start
3. To troubleshoot, added. doesExist returns true, so EF should not attempt to create DB. Doubly so with the SetInitializer set.
using (var myDb = new MyDBContext1())
{
bool doesExist = myDb.Database.Exists(); //return true, the DB does exist!
}
I hope I am wrong, but this seems like a initializer bug in EF that is not honoring my preferences. Please prove me wrong :)
About my setup:
-Using Visual Studio 2013 Preview and EF6 Beta 1
-There is another "Code First" model and DBContext2 (for another DB) in the project. This DB I do own and can create/update the DB to match model changes (if I want to)
-DBContext2 had for some time Code Migrations turned on for it. I deleted all the config and migration table, thinking it may indirectly affect the other context (MyDBContext1), but it didn't help.
--Stack Trace--
//Why is DBMigration and AutoMigrate running here??
//Of course permissions are denied. I don't have SA access (nor need it) to this particular DB that
. I just want to run SELECT statements on.
System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060
Message=CREATE TABLE permission denied in database 'MyDb'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=262
Procedure=""
Server=MyDBServer
State=1
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.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.InternalDispatcher`1.Dispatch[TResult](Func`1 operation, Action`1 executing, Func`3 executed)
at System.Data.Entity.Infrastructure.DbCommandDispatcher.NonQuery(DbCommand command, DbInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass2f.<ExecuteStatements>b__2b()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 func)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action action)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass9.<Update>b__8()
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()
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext)
at System.Data.Entity.Database.Create(Boolean skipExistsCheck)
at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassc`1.<CreateInitializationAction>b__b()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
.....
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__36(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__3c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e()
InnerException:
Do you have a static initializer in MyDBContext1?
static MyDBContext1()
{
Database.SetInitializer<MyDBContext1>(null);
}

Ef 4.x dbcontext generator fails when executed

I have vs2010, installed Entity framework 4.3.1 from nuget, installed the EF 4.x DbContext Generator from microsoft. I create a project then try to add a new EF 4.x DbContext Generator item but the following error. Does anyone know how to resolve this?
Error 1 Running transformation:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.IO.FileNotFoundException:
Unable to locate file at
Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.ResolvePath(String
path) at
Microsoft.VisualStudio.TextTemplating.VSHost.TextTemplatingService.ResolvePath(String
path) --- End of inner exception stack trace --- at
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo
method, Object target, Object[] arguments, SignatureStruct& sig,
MethodAttributes methodAttributes, RuntimeType typeOwner) at
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method,
Object target, Object[] arguments, Signature sig, MethodAttributes
methodAttributes, RuntimeType typeOwner) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture,
Boolean skipVisibilityChecks) at
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.DynamicHost.ResolvePath(String
path) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.MetadataLoader.TryCreateEdmItemCollection(String
sourcePath, String[] referenceSchemas, EdmItemCollection&
edmItemCollection) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.MetadataLoader.CreateEdmItemCollection(String
sourcePath, String[] referenceSchemas) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.MetadataLoader.TryLoadAllMetadata(String
inputFile, MetadataWorkspace& metadataWorkspace) at
Microsoft.VisualStudio.TextTemplatingE78BCB29E8D7A2F9432A449161229C3F.GeneratedTextTransformation.TransformText()
at
Microsoft.VisualStudio.TextTemplating.TransformationRunner.RunTransformation(TemplateProcessingSession
session, String source, ITextTemplatingEngineHost host, String&
result) 1 1
Clearly its a case of PEBKAC. I hadn't created my edmx file. Once I had done this all I needed to do was right click on the model. Select "Add Code Generation item".

Is there a bug in ASP.Net MVC 2 RC version for UpdateModel()?

I'm trying to implement MVC 2 RC version, the latest release of ASP.Net MVC and it can't do a simple Controller.UpdateModel(object) without throwing this exception:
The model of type '[Insert namespace of object being updated here]' could not be updated.
InvalidOperationException
Here's the stack trace:
at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider)
at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model)
at Ccis.Cgov360.Web.InternalApp.Controllers.AdminController.MailingLabelTypeSelected() in C:\Projects\Meadowlark\Development\Meadowlark\Applications\InternalApp\Controllers\AdminController.cs:line 1528
at lambda_method(ExecutionScope , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
When I use MVC Preview 2 it functions and updates the model just fine with no exceptions thrown. I saw elsewhere that there is a bug in RC version, is this the same thing?
I've spent way too much time trying to fix this issue. I was hoping to get the RC release so that we can start using the Html helpers such as TextBoxFor<>, CheckBoxFor<>, etc. and the client-side validation.
To add to Levi's comment, if you catch the exception and return the Edit view, you should see the validation message for the field(s) failing validation, assuming your view contains:
<%= Html.ValidationMessageFor(model => model.name) %>
And your Controller Edit action would contain...
try {
UpdateModel(entity, new [] { "name", "address1", "address2", "city", "state", "zip" } );
TempData["Message"] = "Success";
return RedirectToAction("List");
}
catch {
TempData["Message"] = "Error saving form";
return View(entity);
}
I also ran into this issue.
As a work-around, I am just calling TryUpdateModel() instead of UpdateModel().