how to fix this query of sql - c#

Address TableUserTableThis Query is working perfectly fine in SQL Server Management Studio.
But when I am trying to run this query in C# it gives an exception please help me.
I Have tried many things but unable to resolve this problem.
SQL QUERY
set #LATITUDE=12
set #LONGITUDE=12
Select * FROM [ChefODine].[dbo].[User] Inner Join [ChefODine].[dbo].[Address] on [ChefODine].[dbo].[User].AID=Address.ID
WHERE AID IN (
SELECT Top 5 ID
FROM [ChefODine].[dbo].[Address]
ORDER BY (ABS(ABS(LAT)-ABS(#LATITUDE)))+ABS(ABS(Lng)-ABS(#LONGITUDE)))
C# CODE
public HttpResponseMessage getNearByChef(double lat, double lng)
{
var user = db.Users.SqlQuery("Select * FROM [ChefODine].[dbo].[User] Inner Join [ChefODine].[dbo].[Address] on [ChefODine].[dbo].[User].AID=Address.ID WHERE AID IN( SELECT Top 5 ID FROM[ChefODine].[dbo].[Address] ORDER BY(ABS(ABS(LAT) - ABS("+lat+"))) + ABS(ABS(Lng) - ABS("+lng+"))) ");
return Request.CreateResponse(HttpStatusCode.OK,user);
}
Here is the Exception:
"Message": "An error has occurred.",
"ExceptionMessage": "The 'ObjectContent'1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": null,
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "The data reader is incompatible with the specified 'ChefODineModel.User'. A member of the type, 'Date_time', does not have a corresponding column in the data reader with the same name.",
"ExceptionType": "System.Data.Entity.Core.EntityCommandExecutionException",
"StackTrace": " at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader storeDataReader, EdmMember member, EdmType currentType, Dictionary'2 renameList)\r\n at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary'2 renameList)\r\n at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary'2 renameList)\r\n at System.Data.Entity.Core.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean streaming, EntitySet& entitySet, TypeUsage& edmType)\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)\r\n at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass65'1.b__64()\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func'1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass65'1.b__63()\r\n at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func'1 operation)\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)\r\n at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)\r\n at System.Data.Entity.Internal.Linq.InternalSet'1.<>c__DisplayClass11.b__10()\r\n at System.Data.Entity.Internal.LazyEnumerator'1.MoveNext()\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()"

"The data reader is incompatible with the specified
'ChefODineModel.User'. A member of the type, 'Date_time', does not
have a corresponding column in the data reader with the same name.",
The user object cannot be mapped with ChefODineModel.User because date_time doesn't exist in the Dto Model.
beside that you can use SqlParameter when you have to pass data into the query
public HttpResponseMessage getNearByChef(double lat, double lng)
{
string query = #"Select u.* FROM [ChefODine].[dbo].[User] u
Inner Join [ChefODine].[dbo].[Address] on [ChefODine].[dbo].[User].AID=Address.ID
WHERE AID IN( SELECT Top 5 ID FROM[ChefODine].[dbo].[Address] ORDER BY(ABS(ABS(LAT) - ABS(#LATITUDE))) + ABS(ABS(LATITUDE) - ABS(#LONGITUDE)))";
var user = db.Users.SqlQuery(query, new SqlParameter("#LATITUDE", lat), new SqlParameter("#LONGITUDE", lng)).ToList();
return Request.CreateResponse(HttpStatusCode.OK, user);
}

Related

Query SQL table using Entity Framework

I am new to Entity Framework, and I am trying to query one of my tables, and only return the data from one column. I have used this code:
using (var ctx = new TestEntities())
{
var Pokemon = ctx.C__PokemonName
.SqlQuery("select pokemon from __pokemonname")
.ToList();
foreach (var pokemonname in Pokemon)
MessageBox.Show(Convert.ToString(pokemonname));
}
This code throws an error:
System.Data.Entity.Core.EntityCommandExecutionException
HResult=0x8013193C
Message=The data reader is incompatible with the specified 'TestModel.C__PokemonName'. A member of the type, 'ID', does not have a corresponding column in the data reader with the same name.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader storeDataReader, EdmMember member, EdmType currentType, Dictionary2 renameList)
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary2 renameList)
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary2 renameList)
at System.Data.Entity.Core.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean streaming, EntitySet& entitySet, TypeUsage& edmType)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass691.b__68()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass691.b__67()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Internal.Linq.InternalSet1.<>c__DisplayClass11.b__10()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at PokeForm.Form1..ctor() in F:\VS Projects\PokeForm\PokeForm\Form1.cs:line 28
at PokeForm.Program.Main() in F:\VS Projects\PokeForm\PokeForm\Program.cs:line 19
Easiest way to select * (select all columns) is following:
using (var ctx = new TestEntities())
{
var pokemonList = ctx.C__PokemonName.ToList();
foreach (var pokemon in pokemonList)
MessageBox.Show(Convert.ToString(pokemon.pokemonname));
}
If you want to query only for single column, you should use i.e Dapper-library with custom sql (select pokemonname from __pokemonname) or you can select one column with Linq .Select-operation and projected anonymous type.
using (var ctx = new TestEntities())
{
var pokemonNameList = ctx.C__PokemonName.Select(r => new { pokemonname = r.pokemonname }).ToList();
foreach (var name in pokemonNameList)
MessageBox.Show(Convert.ToString(name.pokemonname));
}

Duplicate type name within an assembly (with NSubstitute)

Since this morning, our CI build failed due to surprising "System.ArgumentException : Duplicate type name within an assembly." exceptions during our tests execution.
(note: our tests project built in .NET (4.6) using references to NUnit (3.9.0.0) and NSubstitute (3.1.0.0).
So far we have step into mscorlib (ModuleBuilder type) and found out that Castle.DynamicProxy was dynamically generating an assembly to host its stubs/fakes/ named: DynamicProxyGenAssembly2. And it seems that we had more than one reference for type named "Castle.Proxies.IEnumerator`1Proxy_13".
We don't really understand what's going on here. We appreciate any suggestion on how to understand and find out a solution.
Stack trace example: -----------------
at System.Reflection.Emit.ModuleBuilder.CheckTypeNameConflict(String strTypeName, Type enclosingType)
at System.Reflection.Emit.AssemblyBuilderData.CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType)
at System.Reflection.Emit.TypeBuilder.Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module, PackingSize iPackingSize, Int32 iTypeSize, TypeBuilder enclosingType)
at System.Reflection.Emit.ModuleBuilder.DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, Int32 typesize)
at System.Reflection.Emit.ModuleBuilder.DefineType(String name, TypeAttributes attr)
at Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, IEnumerable1 interfaces, TypeAttributes flags, Boolean forceUnsigned)
at Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, IEnumerable1 interfaces)
at Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, IEnumerable1 interfaces)
at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.Init(String typeName, ClassEmitter& emitter, Type proxyTargetType, FieldReference& interceptorsField, IEnumerable1 interfaces)
at Castle.DynamicProxy.Generators.InterfaceProxyWithoutTargetGenerator.GenerateType(String typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.<>c__DisplayClass6_0.b__0(String n, INamingScope s)
at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func3 factory)
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)
at NSubstitute.Proxies.CastleDynamicProxy.CastleDynamicProxyFactory.GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, Object[] constructorArguments)
at NSubstitute.Core.SubstituteFactory.Create(Type[] typesToProxy, Object[] constructorArguments, SubstituteConfig config)
at NSubstitute.Routing.Handlers.ReturnAutoValue.<>c__DisplayClass6_0.<ReturnValueUsingProvider>b__0(IAutoValueProvider provider)
at NSubstitute.Routing.Handlers.ReturnAutoValue.Handle(ICall call)
at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate)
at NSubstitute.Routing.Route.Handle(ICall call)
at NSubstitute.Proxies.CastleDynamicProxy.CastleForwardingInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IEnumerable1Proxy_16.GetEnumerator()
at System.Linq.Buffer1..ctor(IEnumerable1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)
at Caraibes.Infrastructure.AggregateCreationAuditTrail.BuildCacheFromEventStore(AggregateType aggregateType) in E:\Builds\TheFuture01_work\366\s\Caraibes\Caraibes.Infrastructure\AggregateCreationAuditTrail.cs:line 45
at Caraibes.Infrastructure.AggregateCreationAuditTrail.HasAlreadyBeenCreated(AggregateType aggregateType, Int32 lightTradeId) in E:\Builds\TheFuture01_work\366\s\Caraibes\Caraibes.Infrastructure\AggregateCreationAuditTrail.cs:line 31
at Caraibes.Tests.Domain.EventSourcing.AggregateCreationAuditTrailShould.Only_call_EventStore_when_previous_request_did_not_contained_the_requested_identifier(AggregateType aggregateType) in E:\Builds\TheFuture01_work\366\s\Caraibes\Caraibes.Tests\Domain\EventSourcing\AggregateCreationAuditTrailShould.cs:line 74
Attachments (0)

Adding OrderBy to an EF query causes OutOfMemoryException

EDIT - This only happens when I add OrderBy before the projection. If I add it after the projection, the query is very quick and has no out of memory problem! I used Linq Pad to check the gen'ed SQL. When I do the order by before the projection the SQL is hundreds of lines longer and has far more projections in it than when it after.
Here's a significantly shortened example of sorting pre projection
from contact in Contacts
orderby contact.ContactID
let DefaultAddress = contact.Addresses.FirstOrDefault(x => x.IsDefault.HasValue && x.IsDefault.Value)
select new {
ContactID = contact.ContactID,
DefaultAddressLine2 = DefaultAddress.Line2
}
And the same example, but sorted post projection
from contact in Contacts
let DefaultAddress = contact.Addresses.FirstOrDefault(x => x.IsDefault.HasValue && x.IsDefault.Value)
select new {
ContactID = contact.ContactID,
DefaultAddressLine2 = DefaultAddress.Line2
} into x
orderby x.ContactID
select x
The second example results in a straight SELECT FROM with a single OUTER APPLY for the address. The first results in two OUTER APPLY's. In the full version of the query, this same "doubling" of the outer apply happens exponentially and I end up with hundreds of extra applys!
ORIGINAL - I have a query to return contacts along with their default address, phone number, and e-mail along these lines
from contact in Db.Contacts
select new
{
Contact = contact,
DefaultAddress = contact.Addresses.FirstOrDefault(x => x.IsDefault.HasValue && x.IsDefault.Value),
DefaultPhone = contact.Phones.FirstOrDefault(x => x.IsDefault.HasValue && x.IsDefault.Value),
DefaultEmail = contact.Emails.FirstOrDefault(x => x.IsDefault.HasValue && x.IsDefault.Value)
} into withDefaults
select new ContactWithDefaultsModel
{
ContactID = withDefaults.Contact.ContactID,
Surname = withDefaults.Contact.ESurname,
First = withDefaults.Contact.EFirst,
// other contact props
DefaultAddressLine2 = withDefaults.DefaultAddress != null ? withDefaults.DefaultAddress.Line2 : null,
DefaultAddressCityID = withDefaults.DefaultAddress != null ? withDefaults.DefaultAddress.CityID : null,
DefaultAddressStateID = withDefaults.DefaultAddress != null ? withDefaults.DefaultAddress.StateID : null,
DefaultAddressCountryID = withDefaults.DefaultAddress != null ? withDefaults.DefaultAddress.CountryID : null,
DefaultAddressZip = withDefaults.DefaultAddress != null ? withDefaults.DefaultAddress.Zip : null,
// same for default phone/email
}
That query works fine, but when I add an OrderBy, even for something simple like OrderBy(x => x.ContactID), the query crashes with an OutOfMemoryException.
I can see from the stack trace that it has something to do with the query plan compiler, but I can't see what the cause is. Here's the full stack trace.
at System.Text.StringBuilder.ToString()
at System.Data.Entity.Core.Metadata.Edm.EdmType.get_Identity()
at System.Data.Entity.Core.Metadata.Edm.TypeUsage.BuildIdentity(StringBuilder builder)
at System.Data.Entity.Core.Metadata.Edm.RowType.GetRowTypeIdentityFromProperties(IEnumerable`1 properties, InitializerMetadata initializerMetadata)
at System.Data.Entity.Core.Metadata.Edm.RowType..ctor(IEnumerable`1 properties, InitializerMetadata initializerMetadata)
at System.Data.Entity.Core.Metadata.Edm.TypeUsage.get_ModelTypeUsage()
at System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateProperty(DbExpression instance, String propertyName, Boolean ignoreCase, EdmMember& foundMember)
at System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.DbExpressionBuilder.PropertyByName(DbExpression instance, String propertyName, Boolean ignoreCase)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.BindingScope.TryResolveVar(Var targetVar, DbExpression& resultExpr)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.ResolveVar(Var referencedVar)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(VarRefOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.VarRefOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(ComparisonOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.ComparisonOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(ConditionalOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.ConditionalOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(FilterOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.FilterOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitAsRelOp(Node inputNode)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.BuildProjection(Node relOpNode, IEnumerable`1 projectionVars)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(SingleRowOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.SingleRowOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitAsRelOp(Node inputNode)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitApply(Node applyNode, DbExpressionKind applyKind)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(OuterApplyOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.OuterApplyOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitAsRelOp(Node inputNode)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitApply(Node applyNode, DbExpressionKind applyKind)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(OuterApplyOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.OuterApplyOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitAsRelOp(Node inputNode)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitApply(Node applyNode, DbExpressionKind applyKind)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(OuterApplyOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.OuterApplyOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitAsRelOp(Node inputNode)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitApply(Node applyNode, DbExpressionKind applyKind)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.Visit(OuterApplyOp op, Node n)
at System.Data.Entity.Core.Query.InternalTrees.OuterApplyOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator.VisitAsRelOp(Node input…tOp.Accept[TResultType](BasicOpVisitorOfT`1 v, Node n)
at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfT`1.VisitNode(Node n)
at System.Data.Entity.Core.Query.PlanCompiler.CTreeGenerator..ctor(Command itree, Node toConvert)
at System.Data.Entity.Core.Query.PlanCompiler.ProviderCommandInfoUtils.Create(Command command, Node node)
at System.Data.Entity.Core.Query.PlanCompiler.CodeGen.Process(List`1& childCommands, ColumnMap& resultColumnMap, Int32& columnCount)
at System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets)
at System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(DbCommandTree ctree, List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)
at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()
I can't say for sure that this will help, but you're giving the plan compiler an awful lot to do that's not necessary. Removing all redundancies, your query could look like this:
from contact in Db.contacts
let DefaultAddress = contact.Addresses.FirstOrDefault(x => x.IsDefault.Value)
let DefaultPhone = contact.Phones.FirstOrDefault(x => x.IsDefault.Value)
let DefaultEmail = contact.Emails.FirstOrDefault(x => x.IsDefault.Value)
select new contactWithDefaultsModel
{
contactID = contact.contactID,
Surname = contact.ESurname,
First = contact.EFirst,
// other contact props
DefaultAddressLine2 = DefaultAddress.Line2,
DefaultAddressCityID = DefaultAddress.CityID,
DefaultAddressStateID = DefaultAddress.StateID,
DefaultAddressCountryID = DefaultAddress.CountryID,
DefaultAddressZip = DefaultAddress.Zip,
// same for default phone/email
}
Here's what I changed:
Removed the projection to an intermediate anonymous type and replaces this by let calls.
Removed all null checks. This can be done safely, because the entire expression is translated into SQL, which doesn't have a null reference concept. In fact, SQL has null propagation that C# now also has, but without the explicit operator (?). Leaving these null checks here will get them translated into the final SQL query, where they're redundant.
This should give the plan compiler less code to chew on and hopefully skirt around this exception.
This issue occurs because you has insufficient memory to allocate for large results.You could sort the list in place, using List.Sort, which uses the Quicksort algorithm. But of course, your original list would be sorted
Contacts.Sort(x => x.CompareTo(ContactID));

Dapper throws "Invalid type owner for DynamicMethod."

So I'm trying to use Dapper.net and I'm liking it. What I'm not liking is when I try to batch-insert entities and I get the following error thrown:
Invalid type owner for DynamicMethod.
at System.Reflection.Emit.DynamicMethod.Init(String name,
MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] signature, Type owner, Module m, Boolean
skipVisibility, Boolean transparentMethod, StackCrawlMark& stackMark)
at System.Reflection.Emit.DynamicMethod..ctor(String name, Type
returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility)
at Dapper.SqlMapper.CreateParamInfoGenerator(Identity identity,
Boolean checkForDuplicates, Boolean removeUnused, IList1 literals) in
D:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 3033 at
Dapper.SqlMapper.GetCacheInfo(Identity identity, Object
exampleParameters, Boolean addToCache) in D:\Dev\dapper-dot-net\Dapper
NET40\SqlMapper.cs:line 2138 at
Dapper.SqlMapper.<QueryImpl>d__611.MoveNext() in
D:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1578 at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param,
IDbTransaction transaction, Boolean buffered, Nullable1
commandTimeout, Nullable1 commandType) in
D:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1479 at
Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param,
IDbTransaction transaction, Boolean buffered, Nullable1
commandTimeout, Nullable1 commandType) in
D:\Dev\dapper-dot-net\Dapper NET40\SqlMapper.cs:line 1418 at
NinjaEvaluation.Data.Database.DapperWrapper.<>c__DisplayClass41.b__3(SqlConnection
sqlConnection, SqlTransaction transaction) in
c:\Projects\InHouse\ninjaevaluation\NinjaEvaluation\NinjaEvaluation.Data\Database\DapperWrapper.cs:line
52 at NinjaEvaluation.Data.Database.DapperWrapper.Invoke(Action`2
action) in
c:\Projects\InHouse\ninjaevaluation\NinjaEvaluation\NinjaEvaluation.Data\Database\DapperWrapper.cs:line
68
This happens in a completely normal situation when I run my query like this:
string sql = #" INSERT INTO XXX
(XXXId, AnotherId, ThirdId, Value, Comment)
VALUES
(#XXXId, #AnotherId, #ThirdId, #Value, #Comment)";
var parameters = command
.MyModels
.Select(model => new
{
XXXId= model.XXXId,
AnotherId= model.AnotherId,
ThirdId= model.ThirdId,
Value = model.Value,
Comment = model.Comment
})
.ToArray();
...
sqlConnection.Query(sql, parameters, commandType: commandType, transaction: transaction)
I found the following SO-thread started by someone having the same problem BUT the issue there seems to have been the .NET version (3.5) but I'm running .NET 4.5 and I can't figure out what the problem is.
Any suggestions?
I ran into this error when using an interface instead of the class:
Query<MyObject> worked, while Query<IMyObject> did not
It fails because this scenario using Query[<T>] isn't expecting an array / sequence of parameters. The Execute call-path does expect this, and unrolls the data automatically, executing the SQL once per item - but this isn't the case for Query[<T>], so it tries to create the dynamic method bound to the array (in your case), which isn't allowed. The code should probably detect this much earlier, and just say "nope, that isn't allowed".
You probably want to change your .ToArray() to .Single().
This will be clearer after the next build; the following passes:
public void SO30435185_InvalidTypeOwner()
{
try {
// not shown for brevity: something very similar to your code
Assert.Fail();
} catch(InvalidOperationException ex)
{
ex.Message.IsEqualTo("An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context");
}
}

Serialize a Dictionary<string, object> that contains a List<string>?

I've found a Serializeable Dictionary which works quite fine: http://www.jankowskimichal.pl/en/2010/10/serializabledictionary/
But I'm getting an exception whenever one of the objects in the dictionary is simply a list of strings. .NET is telling me it can't serialize it:
Serialize 'C:\bin\Debug\Settings\Default.xml' : System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] may not be used in this context.
at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write2_anyType(Object o)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o)
at ShadowBot.Classes.SerializableDictionary`2.WriteXml(XmlWriter writer) in c:\Classes\SerializableDictionary.cs:line 114
at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShadowSettings.Write2_ShadowSettings(String n, String ns, ShadowSettings o, Boolean isNullable, Boolean needType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShadowSettings.Write3_ShadowSettings(Object o)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o)
at Classes.XmlSerializer.Serialize(String Path, Object Object) in c:\Classes\XmlSerializer.cs:line 29
Is this even possible? I'd like this capability and just assumed you could nest objects like this. If this isn't possible, is there a way I can just write the dictionary to disk (doesn't have to be XML) and then re-load it without me having to write custom wrappers for this? I was originally a mac developer and this type of serialization was quite simple, so maybe I'm missing something on .NET.
Edit: When trying odyss' example i get:
System.Runtime.Serialization.SerializationException: Type 'System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with data contract name 'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
I've had similar issues with serializing generic lists. Try changing the list into an string array string[] before serializing and then back to a List<string> after deserializing. This is very easy to do and may solve your problem:
//List<string> to string[]
string[] sArray = sList.ToArray();
//string[] to List<string>
List<string> sList = sArray.ToList();
As an alternative, you might have better luck with System.Runtime.Serialization.DataContractSerializer. Example:
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
dict.Add("test", new List<string>() { "t", "b" });
StringBuilder xmlString = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(xmlString))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, List<string>>));
serializer.WriteObject(writer, dict);
}
This generates:
<?xml version="1.0" encoding="utf-16"?><ArrayOfKeyValueOfstringArrayOfstringty7Ep6D1 xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><KeyValueOfstringArrayOfstringty7Ep6D1><Key>test</Key><Value><string>t</string><string>b</string></Value></KeyValueOfstringArrayOfstringty7Ep6D1></ArrayOfKeyValueOfstringArrayOfstringty7Ep6D1>

Categories