0

I am getting an unknown exception, basicly the following code loops through only 2000 items but it takes a couple of minutes to hit the end opResult = uow.Commit(); and at that point it just says it has failed. I am totally baffled. can any one help please?

public OperationResult PopulateReadingList(int readingListID, PrePopulateType dataType, GroupType[] groups)
        {
            var opResult = new OperationResult();
            var listItemsToReturn = new List<ReadingListItem>();

            try
            {
                Func<short?, Lookup_Countries> getCountry = c => NeptuneUnitOfWork.Countries.FindByID(c);
                Func<string, bool> isEmptyString = string.IsNullOrEmpty;

                using (var uow = NeptuneUnitOfWork)
                {

                    var predicate = BuildPredicate(groups);

                    var items = uow.ReadingList.FindWhere(r=>r.ID==readingListID).SelectMany(m=> m.ReadingListMediaChannels).Where(predicate).ToList();

                    foreach (var readingListMediaChannel in items)
                    {
                        string value = string.Empty;
                        var country = getCountry(readingListMediaChannel.MediaChannel.CountryID);

                        switch (dataType)
                        {
                            case PrePopulateType.Country:
                                value = country != null?country.Name:string.Empty;
                                break;
                            case PrePopulateType.Region:
                                value = country != null?country.Lookup_SubRegions.Lookup_Regions.Name : string.Empty;
                                break;
                            case PrePopulateType.SubRegion:
                                value = country != null ? country.Lookup_SubRegions.Name:string.Empty;
                                break;
                            case PrePopulateType.MediaType:
                                value = readingListMediaChannel.MediaChannel.MediaType.Name;
                                break;
                            default:
                                break;
                        }

                        foreach (var group in groups)
                        {
                            switch (group)
                            {
                                case GroupType.Group1:
                                    if (isEmptyString(readingListMediaChannel.Group1))
                                    {
                                        readingListMediaChannel.Group1 = value;
                                    }
                                    break;
                                case GroupType.Group2:
                                    if (isEmptyString(readingListMediaChannel.Group2))
                                    {
                                        readingListMediaChannel.Group2 = value;
                                    }
                                    break;
                                case GroupType.Group3:
                                    if (isEmptyString(readingListMediaChannel.Group3))
                                    {
                                        readingListMediaChannel.Group3 = value;
                                    }
                                    break;
                                case GroupType.Group4:
                                    if (isEmptyString(readingListMediaChannel.Group4))
                                    {
                                        readingListMediaChannel.Group4 = value;
                                    }
                                    break;
                                case GroupType.Group5:
                                    if (isEmptyString(readingListMediaChannel.Group5))
                                    {
                                        readingListMediaChannel.Group5 = value;
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }

                        listItemsToReturn.Add(new ReadingListItem
                        {
                            Group1 = readingListMediaChannel.Group1,
                            Group2 = readingListMediaChannel.Group2,
                            Group3 = readingListMediaChannel.Group3,
                            Group4 = readingListMediaChannel.Group4,
                            Group5 = readingListMediaChannel.Group5,
                            MediaCode = readingListMediaChannel.MediaChannel.NeptuneMediaID,
                            MediaID = readingListMediaChannel.MediaChannelID,
                            MediaName = readingListMediaChannel.MediaChannel.Name,
                            MediaTypeID = readingListMediaChannel.MediaChannel.MediaTypeID,
                            MediaTypeName = readingListMediaChannel.MediaChannel.MediaType.Name
                        });
                    }

                    opResult = uow.Commit();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                opResult.Success = false;
                opResult.SetExceptionProperties(ex);

            }
            return opResult;
        }

the following is the error message that is returned by the controller that calls this repo:

Source Error:   

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


Stack Trace:     

[ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.]
   System.Data.Objects.ObjectContext.EnsureConnection() +11448512
   System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +66
   System.Data.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption) +229
   System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad() +497
   System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +157
   System.Data.Objects.Internal.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item) +149
   System.Data.Entity.DynamicProxies.ReadingListMediaChan_AA75ADD44097B0AF40DBB84D6E509EE9D2EA11F705268633DBD1D4743DEEA37B.get_MediaChannel() +151

[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) +229
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +193
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +733
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1968
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat) +195
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +1923
   System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember) +166
   System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat) +114
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +282
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +33
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +726368
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +726324
   System.Web.Mvc.Controller.ExecuteCore() +159
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +334
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +15
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +52
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
2
  • 4
    What is the exact error you're getting. I'm sure it should be something more concrete than "failed" Commented May 24, 2013 at 12:09
  • belive it or not i dont get an exception but when the controller that calls this repo returns the above exception. please see the update. thanks Commented May 24, 2013 at 12:17

2 Answers 2

1

Can you move the

Func<short?, Lookup_Countries> getCountry = c => NeptuneUnitOfWork.Countries.FindByID(c);

into the using block, and also use the 'uow' instead:

Func<short?, Lookup_Countries> getCountry = c => uow.Countries.FindByID(c);
Sign up to request clarification or add additional context in comments.

1 Comment

my colleague helped me solve this before your answer but since he did the same thing i gave you a +1 and marked yours as correct.
0

This typically happens when EF lazy loading is enabled and a property that requires lazy loading is accessed after the DbContext or ObjectContext has been disposed.

There are two ways to fix this. Either modify your code to keep the context alive until you've finished with your entities, or disable lazy loading and eager load everything that you need.

When you're working with Web services, the latter option is typically the right one. This is because a service might return entities. The service framework needs to serialize those entities, so it access all their properties. If lazy loading is enabled, this will throw the exception that you're seeing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.