0

我遇到了一个未知的异常,基本上下面的代码只循环了 2000 个项目,但需要几分钟才能结束opResult = uow.Commit();,此时它只是说它失败了。我完全感到困惑。有人可以帮忙吗?

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;
        }

以下是调用此 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
4

2 回答 2

1

你能移动

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

进入 using 块,并使用 'uow' 代替:

Func<short?, Lookup_Countries> getCountry = c => uow.Countries.FindByID(c);
于 2013-05-24T12:34:48.950 回答
0

这通常发生在启用 EF延迟加载并且在处理or之后访问需要延迟加载的属性时。DbContextObjectContext

两种方法可以解决此问题。修改您的代码以使上下文保持活动状态,直到您完成实体,或者禁用延迟加载并急切加载您需要的所有内容。

当您使用Web 服务时,后一种选择通常是正确的选择。这是因为服务可能会返回实体。服务框架需要序列化这些实体,因此它可以访问它们的所有属性。如果启用了延迟加载,这将引发您看到的异常。

于 2013-05-24T13:30:04.183 回答