EF6 Syntax error when getting stored procedure results with parameter - tsql

I don't understand why I'm getting a syntax error when this line of code executes:
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
Here is the whole method:
public virtual ObjectResult<Kitti_getProductGroupDetail_Result> Kitti_getProductGroupDetail(Guid ProductGroupId)
{
var #params = new SqlParameter[]
{
new SqlParameter("ProductGroupId", ProductGroupId)
};
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductGroupDetail_Result>("Kitti_getProductGroupDetail #ProductGroupId", #params);
}
Here is the calling method:
public System.Collections.Generic.IEnumerable<ProductDetail> getProductDetailsFromSP(Guid ProductGroupId)
{
System.Collections.Generic.List<ProductDetail> productDetailList = new System.Collections.Generic.List<ProductDetail>();
using (var context = new EFDbContext())
{
var result = context.Kitti_getProductGroupDetail(ProductGroupId);
foreach (Kitti_getProductGroupDetail_Result res in result)
{
ProductDetail productDetail = new ProductDetail();
productDetail.ProductId = res.productid;
productDetail.SizeId = res.sizeid;
productDetail.SizeDescription = res.sizedescription;
productDetail.SizeRank = res.sizerank;
productDetail.ColorId = res.colorid;
productDetail.ColorDescription = res.colordescription;
productDetail.ColorRank = res.colorrank;
productDetail.QuantityRemainingInStock = res.quantityremaininginstock;
productDetail.ProductGroupId = res.productgroupid;
productDetail.ProductGroupName = "ProductGroupName is currently not in the stored procedure or in EF";
productDetail.Description = res.description;
productDetailList.Add(productDetail);
}
}
return productDetailList;
}
The result object:
public partial class Kitti_getProductGroupDetail_Result
{
public System.Guid productid { get; set; }
public System.Guid productgroupid { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public Nullable<System.Guid> colorid { get; set; }
public string colordescription { get; set; }
public int colorrank { get; set; }
public Nullable<System.Guid> sizeid { get; set; }
public string sizedescription { get; set; }
public int sizerank { get; set; }
public int quantityremaininginstock { get; set; }
public string productname { get; set; }
public string imagesrc { get; set; }
}
Finally here is my stored procedure:
ALTER PROCEDURE [dbo].[Kitti_getProductGroupDetail]
#ProductGroupId uniqueidentifier
-- Insert statements for procedure here
SELECT product.ProductId as 'productid', product.ProductGroupId as 'productgroupid', product.[Description] as 'description'
, product.Price as 'price', product.ColorId as 'colorid', color.ColorDescription as 'colordescription', color.ColorRank as 'colorrank',
product.SizeId as 'sizeid', size.SizeDescription as 'sizedescription', size.SizeRank as 'sizerank', product.QuantityRemainingInStock as 'quantityremaininginstock',
product.Name as 'productname', product.ProductImageSrc as 'imagesrc'
FROM dbo.Product product
INNER JOIN dbo.Color color
on color.ColorId = product.ColorId
INNER JOIN dbo.Size size
on size.SizeId = product.SizeId
INNER JOIN dbo.ProductGroup productgroup
on productgroup.ProductGroupId = product.ProductGroupId
WHERE product.ProductGroupId = #ProductGroupId
AND product.QuantityRemainingInStock > 0
ProductGroupId is definitely getting populated. What doesn't EF like about my code? I have a similar method that does not require a parameter to execute the stored procedure - it works fine
// this works just fine
public virtual ObjectResult<Kitti_getProductDetailsAndCategory_Result> Kitti_getProductDetailsAndCategory()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<Kitti_getProductDetailsAndCategory_Result>("Kitti_getProductDetailsAndCategory");
//ExecuteFunction changed to ExecuteStoreQuery
}
stack trace:
Incorrect syntax near 'Kitti_getProductGroupDetail'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near 'Kitti_getProductGroupDetail'.
Source Error:
Line 40: };
Line 41:
Line 42: return ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery("Kitti_getProductGroupDetail #ProductGroupId", #params);
Line 43: }
Line 44:
Source File: C:\Concrete\EFDbContext.cs Line: 42
Stack Trace:
[SqlException (0x80131904): Incorrect syntax near 'Kitti_getProductGroupDetail'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2444082
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5775560
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) +409
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2127
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +911
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +266
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__68() +44
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__67() +167
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +190
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +462
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery(String commandText, Object[] parameters) +83
KittiCutieFashion.Domain.Concrete.EFDbContext.Kitti_getProductGroupDetail(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:42
KittiCutieFashion.Domain.Concrete.EFDbContext.getProductDetailsFromSP(Guid ProductGroupId) in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFDbContext.cs:82
KittiCutieFashion.Domain.Concrete.EFProductDetailRepository.get_ProductDetail() in C:\KittiCutieFashion\KittiCutieFashion.Domain\Concrete\EFProductDetailRepository.cs:33
KittiCutieFashion.WebUI.Controllers.ProductDetailController.ProductDetailView(String returnUrl) in C:\KittiCutieFashion\KittiCutieFashion.WebUI\Controllers\ProductDetailController.cs:43
lambda_method(Closure , ControllerBase , Object[] ) +103
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2558.0
The version of sql server I am using happens to be 2005 not sure if that has anything to do with it.

Related

The ConnectionString property has not been initialized Entity Framework

The underlying provider failed on Open.
Error Short Description : The ConnectionString property has not been initialized.
Error Inner Description :
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.b__5()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery1..GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.b__1[TResult](IEnumerable1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source)
at SKAI.BusinessLayer.AnalysisTreatmentBL.GetAdviceDetails(Int32 KeywordId)
at SKAI_Dev.Controllers.Analysis.KeywordAnalysisController.GetNeedAdviceDetails(Int32 KeywordId)
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult)

Sitecore 8 Content Editor error

Hey I'm getting this error below, I have tried the solutions here but can seem to fix it. Can someone point me in the right direction.
Any help would be most appreciated!
[NullReferenceException: Object reference not set to an instance of an object.]
Sitecore.PathAnalyzer.Extensions.ItemExtensions.InheritsFromTemplate(Item item, ID templateId, Boolean recursive) +71
Sitecore.PathAnalyzer.Client.Pipelines.GetContentEditorWarnings.TreeDefinitionDeployment.Process(GetContentEditorWarningsArgs args) +68
(Object , Object[] ) +79
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +364
Sitecore.Shell.Applications.ContentManager.Editor.GetWarnings(Boolean hasSections) +270
Sitecore.Shell.Applications.ContentManager.Editor.Render(RenderContentEditorArgs args, Control parent) +177
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.RenderEditor(Item item, Item root, Control parent, Boolean showEditor) +230
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.UpdateEditor(Item folder, Item root, Boolean showEditor) +366
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.Update() +406
Sitecore.Shell.Applications.ContentManager.ContentEditorForm.OnPreRendered(EventArgs e) +211
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +76
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +211
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
Sitecore.Reflection.ReflectionUtil.CallMethod(Type type, Object obj, String methodName, Boolean includeNonPublic, Boolean includeInherited, Object[] parameters) +37
Sitecore.Reflection.ReflectionUtil.CallMethod(Object obj, String methodName, Boolean includeNonPublic, Boolean includeInherited, Object[] parameters) +66
Sitecore.Shell.Applications.ContentManager.ContentEditorPage.OnPreRender(EventArgs e) +117
System.Web.UI.Control.PreRenderRecursiveInternal() +113
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4297

Routing Constraints Errors

I'm using MVC5 with EF6, where in my routing constraints, the "Match" function search for a value in the repository
But there are a lot of errors in my log files related to this search part, such as:
1.
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection was not closed. The connection's current state is connecting.
at System.Data.ProviderBase.DbConnectionClosedConnecting.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
at XXX.Data.Repository`1.Get[T](Expression`1 predicate)
at XXX.Service.AcademicService.GetSubjectBasicModel(Expression`1 predicate)
at XXX.Web.Routing.CourseConstraint.Match(HttpContextBase httpContext, Route route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.ProcessConstraint(HttpContextBase httpContext, Object constraint, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.ProcessConstraints(HttpContextBase httpContext, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context)
at System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
2.
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.
at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
--- End of inner exception stack trace ---
at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__a()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
at XXX.Data.Repository`1.Get[T](Expression`1 predicate)
at XXX.Service.AcademicService.GetSubjectBasicModel(Expression`1 predicate)
at XXX.Web.Routing.CourseConstraint.Match(HttpContextBase httpContext, Route route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.ProcessConstraint(HttpContextBase httpContext, Object constraint, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.ProcessConstraints(HttpContextBase httpContext, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context)
at System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
3.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClassb.<GetResults>b__9()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
at XXX.Data.Repository`1.Get[T](Expression`1 predicate)
at XXX.Service.AcademicService.GetSubjectBasicModel(Expression`1 predicate)
at XXX.Web.Routing.CourseConstraint.Match(HttpContextBase httpContext, Route route, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.ProcessConstraint(HttpContextBase httpContext, Object constraint, String parameterName, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.ProcessConstraints(HttpContextBase httpContext, RouteValueDictionary values, RouteDirection routeDirection)
at System.Web.Routing.Route.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context)
at System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
As you might see, all those errors related to the same "GetSubjectBasicModel",
any ideas how to solve this ?
I'm also attaching my connection string,
<add name="DBContext" connectionString="Data Source=XXX;Initial Catalog=XXX;Persist Security Info=True;User ID=XXX;Password=XXX;Pooling=False" providerName="System.Data.SqlClient" />
I found it - Managing EntityConnection lifetime
it seems that it was multithreading issue,
the problem was solved by creating an instance of context per web request
- https://stackoverflow.com/a/2575501/2981637

Error getting data from second db context instantiated 'through' an interface

Currently working with codefirst v5 on .net 4.5
I have 1 'master' context which includes a locations table called 'Geonames' (snippet below)
public class CoreContext : DbContext
: base("Conn")
{
public DbSet<GeoName> GeoNames { get; set; }
}
The reference here is simply to be able to manage migrations on the table.
Site will have the ability to 'plug-in' different location providers and the geonames table is there to provide a local provider implementation.
The provider is set in the configuration of the website simply setting the classname and namespace of the actual implementation.
It uses an interface like this (simplified)
public interface ILocationProvider
{
IEnumerable<Location> LocationsByName(String Name);
}
The concrete implementation is instantiated as below (simplified)
public static ILocationProvider GetLocationProvider()
{
ILocationProvider Provider = null;
Provider = Activator.CreateInstance(Type.GetType("{selected namespace.classname}")) as ILocationProvider;
}
catch (Exception ex)
{
throw ex;
}
if (Provider == null)
{
throw new NullReferenceException("Could not create an instance of the location Provider");
}
return Provider;
}
The concrete implementation is as follows(simplified)
public class LocalLocationProvider : ILocationProvider
{
public IEnumerable<Location> LocationsByName(string Name)
{
List<Location> locations = new List<Location>();
using (var db = new LocalLocationContext())
{
foreach (var item in db.GeoNames.Where(X => X.Name.Contains(Name)))
{
locations.Add(
new Location { Id = item.Id, Name = item.Name, GeoLocation = item.GeoLocation }
);
}
}
return locations;
}
private class LocalLocationContext : DbContext
{
public LocalLocationContext()
: base("Conn")
{
Database.SetInitializer<LocalLocationContext>(null);
}
public DbSet<GeoName> GeoNames { get; set; }
}
}
The concrete implementation instantiates just fine and I call the method 'LocationsByName' .. but here the trouble starts. When the code line below executes
foreach (var item in db.GeoNames.Where(X => X.Name.Contains(Name)))
{
..
}
I get the following error.
Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296058
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +437
I have tried to instantiate 'LocalLocationContext' without using the 'Activator.CreateInstance()' method I can query the data just fine.
To me it seems obvious that it has got something to do with how I get my actual implemention of the location provider just can't spot what the error or issue is.
Thanks in advance.

Error while calling saveChanges

I received the following error while adding new record
System.Data.Entity.Infrastructure.DbUpdateException was caught
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Navigation.RepositoryBase`2.Add(T entity) in c:\Users\afahmy\Documents\Visual Studio 2012\Projects\Navigation\REpositoryBase.cs:line 174
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Violation of PRIMARY KEY constraint 'PK_dbo.Priorities'. Cannot insert duplicate key in object 'dbo.Priorities'. The duplicate key value is (55c9b08f-1133-4246-9d0b-4f3e5192ffa5).
The statement has been terminated.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=2627
Procedure=""
Server=dbsrv
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException:
The code as follows
public virtual OperationResult Add(T entity)
{
OperationResult opStatus = new OperationResult { Result = QueryResult.Succeeded };
try
{
DataContext.Set<T>().Add(entity);
opStatus.Result = (DataContext.SaveChanges() > 0) ? QueryResult.Succeeded : QueryResult.Failed;
}
catch (Exception exp)
{
opStatus.ExceptionMessage = string.Format(" Error Adding {0}", exp.Message);
opStatus.Result = QueryResult.Failed;
}
return opStatus;
}
Apparently, the entity object has been fetched from the database before. If you add it to the context it will get EntityState.Added, which means that EF will try to insert it. And apparently you generate a primary key value client-side (i.e. not in the database), so EF tries to insert it with an existing PK value.
Since this is the DbContext API (apparent from the Set method, but always helpful to tag explicitly) you can use the IDbSetExtensions.AddOrUpdate method to let EF figure out whether the object needs to be inserted or updated.