Error "Failed to set database initializer of type MyNamespace.MyCustomInitializer, MyAssembly" could not load MyContext type - entity-framework

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/

Related

Querying for owned collection in CosmosDB throws exception when using OData $select (Cannot use ICollection in place of IQueryable)

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?

Multiplicity constraint violated

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.

How to setup Entity Framework / SQL Server with Mono

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"

Request error with WCF Data Services

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.

Invoking a WCF method that takes a List of objects. Consumed via an iPhone application

I have a WCF service that's consumed via an iPhone application. All other methods that accept string parameters or single objects are working fine, however when I invoke a method that takes a "List<CustomObjectClass> ssf".
I am passing an NSMutableArray of CustomObjectClass's to this method and I'm getting the following error:
Any ideas?
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><s:Fault><faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:DeserializationFailed</faultcode><faultstring xml:lang="en-AU">The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:ssf. The InnerException message was 'Error in line 2 position 6. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. '. Please see InnerException for more details.</faultstring><detail><ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><HelpLink i:nil="true"/><InnerException><HelpLink i:nil="true"/><InnerException i:nil="true"/><Message>Error in line 2 position 6. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. </Message><StackTrace> at ReadArrayOfScanShareFriendFromXml(XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)</StackTrace><Type>System.Runtime.Serialization.SerializationException</Type></InnerException><Message>The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:ssf. The InnerException message was 'Error in line 2 position 6. Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. '. Please see InnerException for more details.</Message><StackTrace> at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameter(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, Object[] parameters, Boolean isRequest)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeBody(XmlDictionaryReader reader, MessageVersion version, String action, MessageDescription messageDescription, Object[] parameters, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)
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)</StackTrace><Type>System.ServiceModel.Dispatcher.NetDispatcherFaultException</Type></ExceptionDetail></detail></s:Fault></s:Body></s:Envelope>
It looks like the SOAP message that was sent from iPhone application is not in format expected by the WCF service. If that's the case, you will probably have to take more control over serialization of NSMutableArray of CustomObjectClasses when passing the array to the method.
In order to check whether that is the issue, you could implement and configure WCF message inspector that would write the SOAP request message into a file and then review the file to check whether it looks like following SOAP message:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://tempuri.org/IService/SendData</a:Action>
<a:MessageID>urn:uuid:8a582916-1b9a-47f8-8fb1-c9ff18420391</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">net.tcp://localhost:13031/Service</a:To>
</s:Header>
<s:Body>
<SendData xmlns="http://tempuri.org/">
<ssf xmlns:b="http://schemas.datacontract.org/2004/07/Common"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<!-- Zero or more CustomObjectClass elements-->
<b:CustomObjectClass>
<!-- Zero or more elements for CustomObjectClass properties -->
</b:CustomObjectClass>
</ssf>
</SendData>
</s:Body>
</s:Envelope>
Implement WCF message inspector:
Implement WCF message inspector(IDispatchMessageInspector).
Implement endpoint behavior (IEndpointBehavior).
Implement custom behavior extension element (BehaviorExtensionElement).
WCF message inspector:
public class FileOutputMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest( ref Message request, IClientChannel channel,
InstanceContext instanceContext )
{
string path = Path.Combine(
AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Guid.NewGuid().ToString() + ".xml"
);
File.WriteAllText( path, request.ToString() );
return null;
}
public void BeforeSendReply( ref Message reply, object correlationState )
{ }
}
Endpoint behavior:
public class FileOutputBehavior : IEndpointBehavior
{
public void AddBindingParameters( ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters )
{ }
public void ApplyClientBehavior( ServiceEndpoint endpoint,
ClientRuntime clientRuntime )
{
throw new ApplicationException( "Behavior is not supported on client side." );
}
public void ApplyDispatchBehavior( ServiceEndpoint endpoint,
EndpointDispatcher endpointDispatcher )
{
FileOutputMessageInspector inspector = new FileOutputMessageInspector();
endpointDispatcher.DispatchRuntime.MessageInspectors.Add( inspector );
}
public void Validate( ServiceEndpoint endpoint )
{ }
}
Behavior extension element:
public class FileOutputElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof( FileOutputBehavior ); }
}
protected override object CreateBehavior()
{
return new FileOutputBehavior();
}
}
Configure WCF message inspector:
Declare new behavior extension (Make sure that the correct full type name is used in type attribute).
Use the declared behavior extension in an endpoint behavior.
Reference the endpoint behavior.
Use following configuration as reference:
<system.serviceModel>
<services>
<service name="Server.Service">
<endpoint address=""
binding="netTcpBinding" bindingConfiguration="TCP"
contract="Common.IService"
behaviorConfiguration="RequestMessageToFile"/>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:13031/Service"/>
</baseAddresses>
</host>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="TCP">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="RequestMessageToFile">
<requestFileOutput />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="requestFileOutput"
type="Common.FileOutputElement, Common"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>