I'm trying to setup a very simple test project to evaluate Mono Entity Framework capabilities. When trying to access data, I get a runtime exception about parsing the model data when using .NET Runtime. When using Mono runtime, a stackoverflow exception is thrown.
This seems to be an internal mono bug which occurs when compiling the CSDL Schema Version 3 - see Mono Bugtracker.
So my question is:
How do I setup Mono with Entity Framework to work with a Microsoft SQL Server? Since I don't find much information, should this even be possible? Did anyone of you successfully setup a mono solution using EF and came across similar errors?
This is what I have done so far:
Installed Mono 3.0.1 Beta (latest stable doesn't include EntityFramework.dll)
Setup a Mono Profile for Visual Studio
Disabled strong name verification for delay signed assembilies for
EntityFramework.dll / EntityFramework.SQLServer.dll and added them to the GAC to prevent runtime errors
Created a simple model + added Code Generation Items
written code using the model
The code works with Microsoft EntityFramework.dll (Version 6, Prerelease). When using the Mono equivalent, it looks like there are problems while parsing the entity model:
Exception message (.NET Runtime):
Object reference not set to an instance of an object.
Stacktrace (.NET Runtime):
at System.Xml.XmlTextReaderImpl.InitStreamInput(Uri baseUri, String baseUriStr, Stream stream, Byte[] bytes, Int32 byteCount, Encoding encoding)
at System.Xml.XmlTextReaderImpl..ctor(String url, Stream input, XmlNameTable nt)
at System.Xml.XmlTextReader..ctor(Stream input)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.ComputeSchemaSet(SchemaDataModelOption dataModel)
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.EntityModel.SchemaObjectModel.Schema.SomSchemaSetHelper.GetSchemaSet(SchemaDataModelOption dataModel)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.Schema.Parse(XmlReader sourceReader, String sourceLocation)
at System.Data.Entity.Core.EntityModel.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)
at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.StoreMetadataEntry.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadItemCollection[T](IItemCollectionLoader`1 itemCollectionLoader, T entry)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetOrCreateStoreAndMappingItemCollections(String cacheKey, MetadataArtifactLoader loader, EdmItemCollection edmItemCollection, Object& entryToken)
at System.Data.Entity.Core.EntityClient.EntityConnection.LoadStoreItemCollections(MetadataWorkspace workspace, DbConnection storeConnection, DbConnectionOptions connectionOptions, EdmItemCollection edmItemCollection, MetadataArtifactLoader artifactLoader)
at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
at System.Data.Entity.Core.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<GetEnumerator>m__2C3()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at EntityFrameworkMono.Program.Main(String[] args) in c:\Users\Christopher Dresel\Documents\Visual Studio 2012\Projects\New\EntityFrameworkMono\EntityFrameworkMono\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
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()
Exception message (Mono Runtime):
The requested operation caused a stack overflow.
Stacktrace (Mono Runtime):
at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaElement.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaElement.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
at System.Xml.Schema.XmlSchemaGroupBase.CheckRecursion (Int32 depth, System.Xml.Schema.ValidationEventHandler h, System.Xml.Schema.XmlSchema schema) [0x00000] in <filename unknown>:0
...
This is the code I'm using:
CustomerEntities entities = new CustomerEntities();
var count = entities.Customers.Count(); // Exception throws here
Console.WriteLine(count);
Console.ReadKey();
EDMX file
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="3.0" xmlns:edmx="http://schemas.microsoft.com/ado/2009/11/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="CustomerModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2008" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
<EntityContainer Name="CustomerModelStoreContainer">
<EntitySet Name="Customer" EntityType="CustomerModel.Store.Customer" store:Type="Tables" Schema="dbo" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" />
</EntityContainer>
<EntityType Name="Customer">
<Key>
<PropertyRef Name="CustomerID" />
</Key>
<Property Name="CustomerID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="CustomerName" Type="nvarchar" Nullable="false" MaxLength="50" />
</EntityType>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="CustomerModel" Alias="Self" annotation:UseStrongSpatialTypes="false" xmlns="http://schemas.microsoft.com/ado/2009/11/edm" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntityContainer Name="CustomerEntities" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Customers" EntityType="CustomerModel.Customer" />
</EntityContainer>
<EntityType Name="Customer">
<Key>
<PropertyRef Name="CustomerID" />
</Key>
<Property Name="CustomerID" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Name="CustomerName" Type="String" Nullable="false" MaxLength="50" Unicode="true" FixedLength="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2009/11/mapping/cs">
<EntityContainerMapping StorageEntityContainer="CustomerModelStoreContainer" CdmEntityContainer="CustomerEntities">
<EntitySetMapping Name="Customers">
<EntityTypeMapping TypeName="CustomerModel.Customer">
<MappingFragment StoreEntitySet="Customer">
<ScalarProperty Name="CustomerID" ColumnName="CustomerID" />
<ScalarProperty Name="CustomerName" ColumnName="CustomerName" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
</edmx:Edmx>
And finally the connection string I'm using:
<connectionStrings>
<add name="CustomerEntities"
connectionString="metadata=.\CustomerModel.csdl|.\CustomerModel.ssdl|.\CustomerModel.msl;provider=System.Data.SqlClient;provider connection string="data source=CHRISTOPHERPC\SQLExpress;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient"/>
</connectionStrings>
Dresel, misleading as my reputation may be on this site, I can safely say that using the EntityFramework with mono is not the recommended approach at this time. Although it is technically "supported", the majority of the library is non functional at best. After spending about a month digging as far as I could go, I was unable to peg the possibility of making a fully functioning site above %20. I instead used NHibernate and have been thrilled with the results. And recommend doing the same until the base has solidified further for the EF Mono project. Nhibernate Example (using MySQL, MSSQL supported)
I hope this helps at least a little bit as it's only my sincere thought. Good luck on whatever you choose to do, I know this MS Opensource move can get very "roadblocky"
Related
We are using OData on top of efcore for querying data from CosmosDB (SQL API). The library versions we are using are -
<PackageReference Include="Microsoft.AspNetCore.OData" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Cosmos" Version="6.0.4" />
Our $metadata looks as follows -
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:DataServices>
<Schema Namespace="SampleIksApi.Models" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityType Name="PartnerTenantSubscriptions">
<Key>
<PropertyRef Name="id" />
</Key>
<Property Name="PartnerMPNId" Type="Edm.String" Nullable="false" />
<Property Name="PartnerName" Type="Edm.String" Nullable="false" />
<Property Name="CustomerTenantId" Type="Edm.String" Nullable="false" />
<Property Name="CustomerTenantName" Type="Edm.String" Nullable="false" />
<Property Name="ReportingDate" Type="Edm.DateTimeOffset" Nullable="false" />
<Property Name="id" Type="Edm.String" Nullable="false" />
<Property Name="Subscriptions" Type="Collection(SampleIksApi.Models.PartnerTenantSubscription)" />
</EntityType>
<ComplexType Name="PartnerTenantSubscription">
<Property Name="SubscriptionId" Type="Edm.String" Nullable="false" />
<Property Name="SubscriptionState" Type="Edm.String" Nullable="false" />
<Property Name="PaidStartDate" Type="Edm.DateTimeOffset" />
<Property Name="PaidEndDate" Type="Edm.DateTimeOffset" />
</ComplexType>
</Schema>
<Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm">
<EntityContainer Name="Container">
<EntitySet Name="PartnerTenantSubscriptions" EntityType="SampleIksApi.Models.PartnerTenantSubscriptions" />
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
Our DbContext setup and EDM Model setup for OData are as follows -
var entity = modelBuilder.Entity<PartnerTenantSubscriptions>();
entity.HasNoDiscriminator();
modelBuilder.Entity<PartnerTenantSubscriptions>()
.ToContainer(containerName)
.HasPartitionKey(x => x.PartnerMPNId);
var builder = new ODataConventionModelBuilder();
builder.EntitySet<PartnerTenantSubscriptions>("PartnerTenantSubscriptions");
return builder.GetEdmModel();
This setup works great for regular queries such as simply querying all of the collection or selecting one or more of primitive types such as PartnerName but when I try to select the field 'Subscriptions' which is a collection type, I run into the below error
Query - api/odata/v1.0.0/PartnerTenantSubscriptions?$select=PartnerMPNId,ReportingDate,CustomerTenantId,PartnerAssociationType,CustomerTenantName,Subscriptions
Exception (with full stack trace) -
System.ArgumentException: Expression of type 'System.Collections.Generic.ICollection`1[SampleIksApi.Models.PartnerTenantSubscription]' cannot be used for parameter of type 'System.Linq.IQueryable`1[SampleIksApi.Models.PartnerTenantSubscription]' of method 'System.Linq.IQueryable`1[SampleIksApi.Models.PartnerTenantSubscription] Take[PartnerTenantSubscription](System.Linq.IQueryable`1[SampleIksApi.Models.PartnerTenantSubscription], Int32)' (Parameter 'arg0')
at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
at System.Linq.Expressions.MethodCallExpression.Update(Expression object, IEnumerable`1 arguments)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMemberAssignment(MemberAssignment memberAssignment)
at System.Linq.Expressions.ExpressionVisitor.VisitMemberBinding(MemberBinding node)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMemberInit(MemberInitExpression memberInitExpression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMemberAssignment(MemberAssignment memberAssignment)
at System.Linq.Expressions.ExpressionVisitor.VisitMemberBinding(MemberBinding node)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMemberInit(MemberInitExpression memberInitExpression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMemberAssignment(MemberAssignment memberAssignment)
at System.Linq.Expressions.ExpressionVisitor.VisitMemberBinding(MemberBinding node)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.VisitMemberInit(MemberInitExpression memberInitExpression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosQueryableMethodTranslatingExpressionVisitor.Visit(Expression expression)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at Microsoft.AspNetCore.OData.Query.Container.TruncatedCollection`1..ctor(IQueryable`1 source, Int32 pageSize, Boolean parameterize)
at Microsoft.AspNetCore.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean parameterize, Boolean& resultsLimited)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Microsoft.AspNetCore.OData.Query.ODataQueryOptions.LimitResults(IQueryable queryable, Int32 limit, Boolean parameterize, Boolean& resultsLimited)
at Microsoft.AspNetCore.OData.Query.ODataQueryOptions.ApplyPaging(IQueryable result, ODataQuerySettings querySettings)
at Microsoft.AspNetCore.OData.Query.ODataQueryOptions.ApplyTo(IQueryable query, ODataQuerySettings querySettings)
at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.ExecuteQuery(Object responseValue, IQueryable singleResultCollection, ControllerActionDescriptor actionDescriptor, HttpRequest request)
at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.OnActionExecuted(ActionExecutedContext actionExecutedContext, Object responseValue, IQueryable singleResultCollection, ControllerActionDescriptor actionDescriptor, HttpRequest request)
at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.OnActionExecuted(ActionExecutedContext actionExecutedContext)
at Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at SampleIksApi.Common.Startup.<>c.<<Configure>b__5_0>d.MoveNext() in C:\Users\haridura\source\repos\SampleIksApi\SampleIksApi\Startup.cs:line 37
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I have tried multiple configurations ranging from OwnsMany to setting up ComplexTypes but I cannot seem to get around this issue. Can someone help point me towards what I could be missing here?
I'm getting random errors in some queries using Npgsql.
Here is the stack trace:
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1597
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1497
at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1487
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 1955
at NHibernate.Impl.CriteriaImpl.List(IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 265
at NHibernate.Impl.CriteriaImpl.List[T]() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 276
at LAVASPORT.DAO.MigrarCadeteDAO.findByCompania(Compania compania, String conexion, DateTime fechainicial, DateTime fechafinal) in D:\Aplicaciones\LavaSport\LAVASPORT\DAO\MigrarCadeteDAO.cs:line 125
And here is the message
InnerException = {"57014: canceling statement due to statement timeout"}
I'm not getting this exceptions all the time, just 1 or 2 times at day. The query in special that most send the exception is a high volume query.
Here is the query:
public IList<Cadete> findByCompania(Compania compania, String conexion,DateTime fechainicial,DateTime fechafinal)
{
try
{
DateTime fechaini = new DateTime(fechainicial.Year, fechainicial.Month, fechainicial.Day);
DateTime fechafin = new DateTime(fechafinal.Year, fechafinal.Month, fechafinal.Day);
var nhConfig = new Configuration().Configure(conexion);
var sessionFactory = nhConfig.BuildSessionFactory();
var session = sessionFactory.OpenSession();
session.BeginTransaction();
var query = session.CreateCriteria<Cadete>();
query.CreateAlias("compania", "compania");
query.Add(Restrictions.Eq("compania.id", compania.id))
.Add(Restrictions.Lt("fechaIngreso", fechafin))
.Add(Restrictions.Ge("fechaIngreso",fechaini));
IList<Cadete> cadetes = query.List<Cadete>();
return cadetes;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
return null;
}
This are my NHibernate configuration and my web config file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="LAVASPORT">
<property name="connection.driver_class">NHibernate.Driver.NpgsqlDriver</property>
<property name="connection.connection_string">
Server=localhost;database=LAVASPORT;user id=postgres;password=admin;MaxPoolSize=500;TimeOut=1000;
</property>
<property name="dialect">NHibernate.Dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<mapping assembly="LAVASPORT"/>
</session-factory>
</hibernate-configuration>
If I increase the timeout to more than 1000, I get errors on connections every time.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"></section>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
<system.transactions>
<defaultSettings timeout="10:00:00" />
</system.transactions>
</configuration>
I would really appreciate any help.
First, note that the Timeout connection string parameter manages connection timeouts (i.e. NpgsqlConnection.Open()) rather than command execution timeout. Defaul command execution timeout is managed via the Command Timeout connection string parameter.
Beyond that, it seems like your commands are simply timing out. Since the default command timeout is 30 seconds, it would seem you have some serious performance issue with your queries, your database index, or something else. You need to carefully analyze the SQL being created by NHibernate and how it's executed by PostgreSQL.
I have two entites:
ClaimDetail (int ID, IList ClaimDetailStatus, other...)
ClaimDetailStatus (int ID, ClaimDetailClaimDetail, other...)
Configuration:
modelBuilder.Entity<ClaimDetailStatus>()
.HasRequired<ClaimDetail>(x => x.ClaimDetail)
.WithMany(x => x.ClaimDetailStatus)
.HasForeignKey(x => x.ClaimDetailID).WillCascadeOnDelete(true);
modelBuilder.Entity<ClaimDetail>()
.HasMany<ClaimDetailStatus>(x => x.ClaimDetailStatus)
.WithRequired(x => x.ClaimDetail)
.HasForeignKey(x => x.ClaimDetailID).WillCascadeOnDelete(true);
When i'm writing the code, running & debug it everything is fine but when i want to save everything it throws an exception:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Multiplicity constraint violated. The role 'ClaimDetailStatus_ClaimDetail_Target' of the relationship 'EPer.DataAccess.ClaimDetailStatus_ClaimDetail' has multiplicity 1 or 0..1.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.DataClasses.EntityReference`1.AddToLocalCache(IEntityWrapper wrappedEntity, Boolean applyConstraints)
at System.Data.Objects.EntityEntry.TakeSnapshotOfSingleRelationship(RelatedEnd relatedEnd, NavigationProperty n, Object o)
at System.Data.Objects.EntityEntry.TakeSnapshotOfRelationships()
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityCollection`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at EPer.DataAccess.ObjectSetAdapter`1.AddObject(T entity) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.Dal\ObjectSetAdapter.cs:line 41
at EPer.BusinessLogic.DomainServices.ClaimComponent.CreateClaim(Claim claimModel, UserClaim uc) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\DomainServices\ClaimComponent.cs:line 28
at EPer.BusinessLogic.ApplicationServices.ClaimService.CreateClaim(Claim claimModel, IEnumerable`1 autoApprovers, UserClaim uc) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\ApplicationServices\ClaimService.cs:line 180
at EPer.BusinessLogic.ApplicationServices.ClaimService.CreateClaim(Claim claimModel, IEnumerable`1 autoApprovers) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\ApplicationServices\ClaimService.cs:line 113
at EPer.BusinessLogic.ApplicationServices.ClaimService.CreateClaim(Claim claimModel) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer.BusinessLogic\ApplicationServices\ClaimService.cs:line 99
at EPer.Areas.Claims.Controllers.ClaimController.Create(SingleClaim m) in c:\KBData\_repo\Intranet\Apps\EOffice\EPer\EPer\Areas\Claims\Controllers\ClaimController.cs:line 107
at lambda_method(Closure , ControllerBase , Object[] )
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.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
Generated association:
<Association Name="ClaimDetailStatus_ClaimDetail">
<End Role="ClaimDetailStatus_ClaimDetail_Source" Type="Self.ClaimDetailStatus" Multiplicity="*" />
<End Role="ClaimDetailStatus_ClaimDetail_Target" Type="Self.ClaimDetail" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
<ReferentialConstraint>
<Principal Role="ClaimDetailStatus_ClaimDetail_Target">
<PropertyRef Name="ID" />
</Principal>
<Dependent Role="ClaimDetailStatus_ClaimDetail_Source">
<PropertyRef Name="ClaimDetailID" />
</Dependent>
</ReferentialConstraint>
I have checked the generated visualized Entity Data Model and everything looked okay.
What is happening here?
EDIT correction
I have a 3rd entity: Claim; if a Claim contains only one ClaimDetail everything works fine but if it contains 2 ClaimDetail the above exception is thrown.
The problem was that i added to each of the ClaimDetail's ClaimDetailStatus collection the same instance of the first ClaimDetailStatus. If i'm adding different instances (in a cycle detail.ClaimDetailStatus.Add(new ...)) everything works fine.
ClaimDetail (int ID, IList ClaimDetailStatus, other...)
ClaimDetailStatus (int ID, ClaimDetailClaimDetail, other...)
This happened when I got entity from db, then tried to save the edited one.
Try
Detached ClaimDetail.ClaimDetailStatus.ClaimDetailClaimDetail,
ClaimDetail.ClaimDetailStatus,
ClaimDetail
Then save, it works.
I'm creating a web app using .NET4.5 with Entity Framework 6 alpha3 that uses a new SQL Compact database. The database does not yet exist.
I have the following code in a web form:
public IQueryable<Job> listJobs_GetData()
{
var db = new JournalistContext();
IQueryable<Job> query = db.Jobs.Where(d => d.JobStart > DateTime.Now)
.OrderBy(s => s.JobStart)
.Take(10);
return query;
}
where the JournalistContext derives from DbContext.
It creates the instance of JournalistContext ok, but when executing the next line, it throws the exception below.
I'm guessing as the database doesnt exist, it tries to call the initializer, but this fails.
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Failed to set database initializer of type 'TSJ.Models.MyCustomInitializer, TSJ' for DbContext type 'TSJ.JournalistContext, TSJ' specified in the application configuration. See inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage)
at System.Data.Entity.Internal.InitializerConfig.<>c__DisplayClass6.<TryGetInitializerFromEntityFrameworkSection>b__1(ContextElement e)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Internal.InitializerConfig.TryGetInitializerFromEntityFrameworkSection(Type contextType)
at System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type contextType)
at System.Data.Entity.Config.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
at System.Data.Entity.Config.AppConfigDependencyResolver.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.Config.AppConfigDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Config.ResolverChain.<>c__DisplayClass3.<GetService>b__0(IDbDependencyResolver r)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Config.ResolverChain.GetService(Type type, Object key)
at System.Data.Entity.Config.CompositeResolver`2.GetService(Type type, Object key)
at System.Data.Entity.Config.IDbDependencyResolverExtensions.GetService(IDbDependencyResolver resolver, Type type)
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 TSJ.MainOverview.listJobs_GetData() in ....\Visual Studio 2012\Projects\TSJ\TSJ\MainOverview.aspx.cs:line 27
InnerException: System.TypeLoadException
HResult=-2146233054
Message=Could not load type 'TSJ.JournalistContext' from assembly 'TSJ'.
Source=mscorlib
TypeName=TSJ.JournalistContext
StackTrace:
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError)
at System.Data.Entity.Internal.InitializerConfig.TryGetInitializer(Type requiredContextType, String contextTypeName, String initializerTypeName, Boolean isDisabled, Func`1 initializerArgs, Func`3 exceptionMessage)
As described here http://msdn.microsoft.com/en-us/data/jj556606 I have created a custom database initializer, which presently is a blank class:
internal sealed class MyCustomInitializer : MigrateDatabaseToLatestVersion<JournalistContext, TSJ.Migrations.Configuration>
{
}
public class JournalistContext : DbContext
{
public JournalistContext() : base("TSJ")
{
}
...
My web.config file references this initializer as follows:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<contexts>
<context type="TSJ.JournalistContext, TSJ">
<databaseInitializer type="TSJ.Models.MyCustomInitializer, TSJ" />
</context>
</contexts>
<providers>
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</providers>
</entityFramework>
I'm stumped! Any ideas?
Another thing I've noticed: these lines have appeared in my web.config file. I'm not sure how they were added, or why.
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
many thanks, Mark.
My guess is that your initializer class is internal. In my project I was loading it from another assembly and it could not see it. Once I changed to public it worked like magic.
I assume that it may be true even if you have everything in the same assembly.
My problem was related to my connection string.
Man, after trying the following links, I had no success. I was trying to connect to my SQLEXPRESS instance. I tried:
error loading database initializer with EF6
Reset Entity-Framework Migrations
Try this instead - this finally worked for me. Replace the data source with your SqlExpress/SqlServer instance if you aren't using localdb.
Enable-Migrations -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=[your database name];User Id=[your user name];Password=[your password];Integrated Security=SSPI;" -ConnectionProviderName "System.Data.SqlClient" -Force -Verbose
Add-Migration -Name "Initial" -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=[your database name];User Id=[your user name];Password=[your password];Integrated Security=SSPI;" -ConnectionProviderName "System.Data.SqlClient" -Force -Verbose
Update-Database -Force -ConnectionString "Data Source=.\SQLEXPRESS;Initial Catalog=[your database name];User Id=[your user name];Password=[your password];Integrated Security=SSPI;" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Feel free to comment and I can continue trying to assist if you're still having this problem.
This was the resource I finally found that helped me understand a lot about what I'm doing.
https://coding.abel.nu/2012/03/ef-migrations-command-reference/
Its my first time setting up an OData Service and I'm of course having some problems...
The problem is that I can't get the service running, I keep getting an "Request Error".
I have researched on what the problem can be and I found that a common issue is that the access rules are incorrectly typed. So I have tried fixing this both with Singular names, Plural names and I have also tried with typeof(Post).getType().Name
Well here is my code. I hope you can help me, I've been stuck for hours.
public class ODataService : DataService<Entity>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService( DataServiceConfiguration config )
{
//config.SetEntitySetAccessRule( "Users", EntitySetRights.All );
//config.SetEntitySetAccessRule( "Posts", EntitySetRights.All );
//config.SetEntitySetAccessRule( "Albums", EntitySetRights.All );
config.SetEntitySetAccessRule( "*", EntitySetRights.AllRead );
config.SetServiceOperationAccessRule( "*", ServiceOperationRights.AllRead );
//config.SetServiceOperationAccessRule( "GetPosts", ServiceOperationRights.AllRead );
config.UseVerboseErrors = true;
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
[WebGet]
public IQueryable<Post> GetPosts()
{
return CurrentDataSource.Posts.AsQueryable();
}
}
The structure of my EntityFramework class (db first)
Methods and Members for Entity class. Here the entities are spelled in plural.
This is my Web.config:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="Entity" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="data source=XXX;Initial Catalog=XXX;persist security info=True;user id=XXX;password=XXX;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime requestValidationMode="4.5" targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<pages controlRenderingCompatibilityVersion="4.5" />
<machineKey compatibilityMode="Framework45" />
</system.web>
<system.serviceModel>
<services>
<service name="LinkIT.Core.OData.ODataService" behaviorConfiguration ="DebugEnabled">
</service>
</services>
<behaviors>
<serviceBehaviors >
<behavior name="DebugEnabled">
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
</configuration>
A detailed error message:
The server encountered an error processing the request. The exception
message is 'Value cannot be null. Parameter name:
propertyResourceType'. See server logs for more details. The exception
stack trace is:
at System.Data.Services.WebUtil.CheckArgumentNull[T](T value, String
parameterName) at
System.Data.Services.Providers.ResourceProperty..ctor(String name,
ResourcePropertyKind kind, ResourceType propertyResourceType) at
System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMemberMetadata(ResourceType
resourceType, IProviderMetadata workspace, IDictionary2 knownTypes,
PrimitiveResourceTypeMap primitiveResourceTypeMap) at
System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(IDictionary2
knownTypes, IDictionary2 childTypes, IDictionary2 entitySets) at
System.Data.Services.Providers.BaseServiceProvider.PopulateMetadata()
at System.Data.Services.Providers.BaseServiceProvider.LoadMetadata()
at
System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider&
metadataProviderInstance, IDataServiceQueryProvider&
queryProviderInstance, BaseServiceProvider& builtInProvider, Object&
dataSourceInstance) at
System.Data.Services.DataService1.CreateProvider() at
System.Data.Services.DataService1.HandleRequest() at
System.Data.Services.DataService1.ProcessRequestForMessage(Stream
messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] ,
Object[] ) at
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs) at
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&
rpc) at
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&
rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean
isOperationContextSet)
WCF Data Services team confirms - this is the exact error faced when you use Enums (which is not yet supported).
Remove the Enum types (or use their suggested work-around and use a wrapper around the enum properties) and this should go away.