Multiple odata webapi controllers with the same resultset - entity-framework

I need to create two odata controllers that return the same result set.
Specifically, the result sets is returned from two stored procedures, which receive a lot of parameters, and do some heavy processing on server.
Both SPs receive exact the same params and return the same data, but they accomplish the search in different ways, and I need to do this for some performance tests and comparisons.
The SPs are mapped to functions in EF.
So I need to have two odata controllers that, each of them, call a different SP, but return the same data type.
My code is as follows:
Controller 1
<Authorize>
Public Class SearchController
Inherits ODataController
Private _dc As New ModelDC
' GET odata/Search
<Queryable>
Function GetSearch(<FromURI> search As SearchParam) As IQueryable(Of SearchResult)
dim result = _dc.Search(search.Parm1, search.Param2, ...).ToList
Return result.AsQueryable
end function
Controller 2
<Authorize>
Public Class SearchV2Controller
Inherits ODataController
Private _dc As New ModelDC
' GET odata/Search
<Queryable>
Function GetSearch(<FromURI> p1 as string, <FromURI> p2 as string, ...) As IQueryable(Of SearchResult)
dim result = _dc.SearchV2(p1, p2, ...).ToList
Return result.AsQueryable
end function
And the odata route registration in WebApiConfig.Register
Dim builder As New ODataConventionModelBuilder
builder.EntitySet(Of SearchResult)("Search")
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel())
builder = New ODataConventionModelBuilder
builder.EntitySet(Of SearchResult)("SearchV2")
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel())
However, when I start the app, I get the following error:
Server Error in '/' Application. Exception of type
'System.OutOfMemoryException' was thrown. 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.OutOfMemoryException: Exception of type
'System.OutOfMemoryException' was thrown.
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:
[OutOfMemoryException: Exception of type 'System.OutOfMemoryException'
was thrown.] System.Reflection.RuntimeAssembly._nLoad(AssemblyName
fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder,
Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) +0
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String
codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint,
StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) +34
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly,
StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
throwOnFileNotFound, Boolean forIntrospection, Boolean
suppressSecurityChecks) +152
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr
pPrivHostBinder, Boolean forIntrospection) +77
System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean
forIntrospection) +16 System.Reflection.Assembly.Load(String
assemblyString) +28
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String
assemblyName, Boolean starDirective) +38
[ConfigurationErrorsException: Exception of type
'System.OutOfMemoryException' was thrown.]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String
assemblyName, Boolean starDirective) +736
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory()
+217 System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo
ai) +130
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection
compConfig) +170
System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies()
+91 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String
preStartInitListPath, Boolean& isRefAssemblyLoaded) +284
System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
appManager, IApplicationHost appHost, IConfigMapPathFactory
configMapPathFactory, HostingEnvironmentParameters hostingParameters,
PolicyLevel policyLevel, Exception appDomainCreationException) +521
[HttpException (0x80004005): Exception of type
'System.OutOfMemoryException' was thrown.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9930508
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +254
What is the problem?
Is it the fact that both controllers are defined with the same return type?
I can, of course, create a different entity for the second SP (with exact the same structure), and map the result of each SP to different result class, and I assume that will work, but I prefer to have them both returning the same type of result.
What am I doing wrong?
Thanks
PS. I have the result converted first ToList and then returned AsQueryable because I need to support $inlinecount odata param, and EF-mapped SPs uses DataReader inside, which doesn't allow to re-enumerate the set to get the count first and then return the actual data. If anyone has a better idea to handle this, please let me know also.

why do you map the same route with different Edm Model? Can you merge them together as?
Dim builder As New ODataConventionModelBuilder
builder.EntitySet(Of SearchResult)("Search")
builder.EntitySet(Of SearchResult)("SearchV2")
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel())

Related

SqlPackage Object reference not set to an instance of an object

When I attempt to deploy DACPACs via SqlPackage.exe,
I encounter the error below :
An unexpected failure occurred: Object reference not set to an instance of an object..
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.Sql90TableBaseColumnPopulator`1.InsertElementIntoParent(SqlColumn element, TElement parent, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.CreateChildElement(TParent parent, EventArgs e, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.PopulateAllChildrenFromCache(IDictionary`2 cache, SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.TopLevelElementPopulator`1.Populate(SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulators(ReliableSqlConnection conn, IList`1 populators, Int32 totalPopulatorsCount, Int32 startIndex, Boolean progressAlreadyUpdated, ReverseEngineerOption option, SqlReverseEngineerRequest request)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulatorsInPass(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, SqlReverseEngineerRequest request, Int32 totalCount, Tuple`2[] populatorsArray)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.PopulateBatch(SqlReverseEngineerConnectionContext context, SqlSchemaModel model, ReverseEngineerOption option, ErrorManager errorManager, SqlReverseEngineerRequest request, SqlImportScope importScope)
at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineer.PopulateAll(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, ErrorManager errorManager, Boolean filterManagementScopedElements, SqlImportScope importScope, Boolean optimizeForQuery, ModelStorageType modelType)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.ImportDatabase(SqlReverseEngineerConstructor constructor, DeploymentEngineContext context, ErrorManager errorManager)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.OnLoad(ErrorManager errors, DeploymentEngineContext context)
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.PrepareModels()
at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.InitializePlanGeneratator()
at Microsoft.SqlServer.Dac.DacServices.<>c__DisplayClass21.<CreateDeploymentArtifactGenerationOperation>b__1f(Object operation, CancellationToken token)
at Microsoft.SqlServer.Dac.Operation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.ReportMessageOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.Execute(IOperation operation, DacLoggingContext loggingContext, CancellationToken cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(DacPackage package, String targetDatabaseName, DacDeployOptions options, Nullable`1 cancellationToken)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.<>c__DisplayClasse.<DoDeployAction>b__4(DacServices service)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.ExecuteDeployOperation(String connectionString, String filePath, MessageWrapper messageWrapper, Boolean sourceIsPackage, Boolean targetIsPackage, Func`1 generateScriptFromPackage, Func`2 generateScriptFromDatabase)
at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.DoDeployAction(DeployArguments parsedArgs, Action`1 writeError, Action`2 writeMessage, Action`1 writeWarning)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.DoDeployActions(CommandLineArguments parsedArgs)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Run(String[] args)
at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Main(String[] args)
Below is the command I run:
SET vardeploy2=/Action:Script
set varBlockOnDriftParameter=/p:BlockWhenDriftDetected=False
"SSDTBinaries\SqlPackage.exe" %vardeploy2% %varBlockOnDriftParameter% /SourceFile:"dacpacs\DBName.dacpac" /Profile:"Profiles\%1.DBName.Publish.xml" >> Log.txt 2>>&1
I deploy to a SQL Server 2008 R2. The SqlPackage.exe version is 11.0.2820.0.
The issue is intermittent, which suggests it's not related to the DACPAC being deployed or the destination database's schema. My best guess is that something about the state of the database is causing the problem.
Still, I haven't been able to identify anything unusual at the time of the failures.
When recreating the issue locally, using schema locks results in a different error message.
Has anyone know of a solution?
Upgrade to a more resent SQL Server Data Tools.

"An unexpected error ocurred" CRM2015 OnPremise Plugins

For 2 weeks we have been experiencing a small totally random issue with plugins in CRM 2015 OnPremise. When we make an upload, randomly and without much sense (at least according to analyze all code does not) plugins are throwing us the following exception:
The Web Service plug-in failed in OrganizationId:
fb2630bc-8dc1-e411-80be-bae05bad392c; SdkMessageProcessingStepId:
d2713f4e-51b7-e411-80b8-527d00dcf108; EntityName: new_serviciobase;
Stage: 30; MessageName: Create; AssemblyName:
Microsoft.Crm.Extensibility.InternalOperationPlugin,
Microsoft.Crm.ObjectModel, Version=7.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35; ClassName:
Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception:
Unhandled Exception: System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
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.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object
target, Object[] values)
at
Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider
serviceProvider)
at
Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext
context)
at
Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext
context)
Inner Exception: System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type,
Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at
Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.InitializePlugin[T](IOrganizationContext
context, StepDescription stepDescription, SecureConfigurationCache
stepSecureConfigurationCache, Type type)
at Microsoft.Crm.Extensibility.V5PluginProxyStep..ctor(Guid stepId,
SecureConfigurationCache stepSecureConfigurationCache, CrmEventLog
eventLog, IOrganizationContext context)
at Microsoft.Crm.Extensibility.PluginStep..ctor(Guid stepId,
SecureConfigurationCache stepSecureConfigurationCache, CrmEventLog
eventLog, IOrganizationContext context)
at
Microsoft.Crm.Extensibility.PipelineStepFactory.CreateInstance(Guid
stepId, IOrganizationContext context)
at Microsoft.Crm.Caching.PipelineStepCacheLoader.LoadCacheData(Guid
key, ExecutionContext context)
at
Microsoft.Crm.Caching.ObjectModelCacheLoader`2.LoadCacheData(TKey key,
IOrganizationContext context)
at
Microsoft.Crm.Caching.CrmMultiOrgCacheBase`2.CreateEntry(TKey key,
IOrganizationContext context)
at Microsoft.Crm.Caching.CrmSharedMultiOrgCache`2.LookupEntry(TKey
key, IOrganizationContext context)
at
Microsoft.Crm.Caching.MessageProcessorCacheLoader.GetCustomizationLevel(MessageProcessor
mp, ExecutionContext context)
at
Microsoft.Crm.Caching.MessageProcessorCacheLoader.LoadCacheData(MessageProcessorKey
key, ExecutionContext context) at
Microsoft.Crm.Caching.ObjectModelCacheLoader`2.LoadCacheData(TKey key,
IOrganizationContext context)
at Microsoft.Crm.Caching.CrmSharedMultiOrgCache`2.LookupEntry(TKey
key, IOrganizationContext context)
at
Microsoft.Crm.Extensibility.InternalMessageDispatcher.TryGetMessageProcessor(MessageProcessorKey
key, ExecutionContext context)
at
Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.IsPipelineDefined(MessageProcessorKey
key, ExecutionContext context)
at
Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.CreateWithInvocationSource(BusinessEntity
entity, Int32 invocationSource, ExecutionContext context)
at
Microsoft.Crm.BusinessEntities.BusinessProcessObject.Create(IBusinessEntity
entity, ExecutionContext context)
Inner Exception: System.IO.FileLoadException: Could not load file or
assembly ‘SCM.CRM.Core, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=369abd01f82b8d9d’ or one of its dependencies. Access is
denied.
at SCM.CRM.Plugins.Plugin..ctor(Type childClassName)
at SCM.CRM.Plugins.PLGServicioBase..ctor()
It brings a little headache because we don't understand what happened, just that sometimes fails and sometimes not ... we have a custom library registered plugins (disk) "SCM.Core.dll" to which says itself unable to access ... Any ideas?
As #Sxntk said, you need to make sure you merge any plugins with ilmerge if you are using Sandbox mode isolation mode when registering the plugin assembly.
If you have an isolation mode of 'none', make sure the assembly is in the GAC or placed in the bin\assembly folder in the CRM installation directory on the server.
Hopefully this helps.
I'm a coleague of Alexis, and now we have more details thanks to crmdiagtool:
System.IO.FileLoadException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #ED0C936C: System.IO.FileLoadException: Could not load file or assembly 'SCM.CRM.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=369abd01f82b8d9d' or one of its dependencies. Access is denied.
File name: 'SCM.CRM.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=369abd01f82b8d9d'
You can do the following thing:
make sure all your referenced assemblies have "Copy Local" set to "True"
unload the project from visual studio
right click on the unloaded project and edit the csproj file
add the following lines in the csproj file right before the "Project" end tag (before last line in the document):
<Target Name="AfterResolveReferences">
<ItemGroup>
<EmbeddedResource Include="#(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
<LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
</EmbeddedResource>
</ItemGroup>
</Target>
add this method to the plugin class:
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(args.Name);
string path = assemblyName.Name + ".dll";
if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false)
{
path = String.Format(#"{0}\{1}", assemblyName.CultureInfo, path);
}
using (Stream stream = executingAssembly.GetManifestResourceStream(path))
{
if (stream == null)
return null;
byte[] assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
add the following constructor to the plugin class:
static [Constructor name]()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
}
rebuild and register your plugin
Doing this, all the referenced assemblies that are copied locally to your bin folder are packed into the main dll. The drawback is that you could end up having such a huge dll that you can not register it as a plugin.
Hope this helps,
Cheers

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);
}

find out the exact entity causing an exception in entity framework

The entity framework gives me generic messages in the exception without telling me the exact entity and the attribute which caused the error. How do I get more information about the error?
This happens in many cases such as
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
and
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
Exception details:
[SqlException (0x80131904): The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +404
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2660
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +118
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6431425
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +6432994
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +538
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +28
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +256
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +19
System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues) +270
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +391
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +11223976
System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) +833
System.Data.Entity.Internal.InternalContext.SaveChanges() +218
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +291
Here's the code I have in my solution:
try
{
_context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
//raise a new exception inserting the current one as the InnerException
raise = new InvalidOperationException(message , raise);
}
}
throw raise;
}
You can use it as a basis to add into your solution ... it builds a nested set of exceptions with all the details from Entity Framework.
You need to write tests for repositories and in the base class for your tests:
try
{
DbContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
throw;
}