ObjectContext实例已被处理,不能再用于需要连接错误的操作

本文关键字:连接 错误 操作 用于 实例 处理 不能 ObjectContext | 更新日期: 2023-09-27 18:02:51

我一直在Visual Studio 2012中使用实体框架(数据库优先)的项目上工作。它是ASP。. NET MVC项目(c#),razor。在视图中,我有一个剑道网格:

@(Html.Kendo().Grid<RunSummary>()
          .Name("CheckedPatients")                    
          .DataSource(datasource => datasource                
                .Ajax().PageSize(25)        
                .ServerOperation(false)                           
                .Sort(sort => sort.Add("TimeOn").Descending())
                .Read(read => read.Action("GetRunSummaries", "PatientReport")))              
          .Columns(columns =>
              {
                  columns.Bound(c => c.UniqueId).Title(ELSORegistry.Resources.Views.Home.HomeStrings.UniqueId)
                      .ClientTemplate("<input type='checkbox'  class='primaryBox'  id='#= UniqueId #' value='#= UniqueId #'>#= UniqueId #</input>");                        
                  columns.Bound(c => c.RunNo).Title(SharedStrings.Run);
                  columns.Bound(c => c.Birthdate).Title(SharedStrings.Birthdate).Format("{0:g}").Filterable(true);
                  columns.Bound(c => c.customAge).Title(SharedStrings.Age)
                         .Filterable(
                             filterable => filterable
                                 .UI("AgeFilter")
                                 .Extra(false)
                                 .Operators(operators => operators
                                     .ForString(str => str.Clear().IsEqualTo("Is equal to"))
                                     )
                       );
                  columns.Bound(c => c.TimeOn).Title(PatientStrings.DateOn)
                      .Format("{0:g}")
                      .Filterable(true);
                  columns.Bound(c => c.TimeOff).Title(PatientStrings.DateOff)
                      .Format("{0:g}")
                      .Filterable(true);
                  columns.Bound(c => c.DischargedAlive).Title(PatientStrings.DischargedAlive).Filterable(true);//.ClientTemplate("#= DischargedAlive ? 'Yes' : 'No' #");
                  columns.Bound(c => c.ShowSubmitted).Title(PatientStrings.Submitted).Filterable(true);//.ClientTemplate("#= ShowSubmitted ? 'Yes' : 'No' #");
                  columns.Bound(c => c.SupportTypeEnum).Title(PatientStrings.SupportType).Filterable(true);//.ClientTemplate("#= SupportType ? 'Yes' : 'No' #");
              }
          )
          .Pageable(p => p.PageSizes(new[] {10, 25, 50, 100}))
          .Sortable()
          .Filterable( )
          .Events( e => e.FilterMenuInit("FilterMenuFuncWithAge") ) // apply x [closing box] on pop up filter box
          )

作为Kendo Grid的源,我使用了一个存储过程:

CREATE PROCEDURE [dbo].[IGD_spPatientListReportFillGrid]
(@CenterId uniqueidentifier)

AS
BEGIN
 SET NOCOUNT ON
-- DECLARE @start DATETIME, @end DATETIME;
-- SET @start = GETDATE();

  SELECT R.RunId, R.submittedDate, R.CompletedBy, R.isRunLocked, R.LockDate, P.isPatientLocked, DATEDIFF(DAY, ISNULL
(R.submittedDate, GETDATE()), GETDATE()) 
                         AS DaysDiff, CP.CenterId, P.PatientId,
                         P.UniqueId,
                         R.RunNo,
                         R.SupportType,
                         CAST(P.Birthdate AS DATETIME) AS Birthdate,
                         P.Sex, P.Race, 
                         R.Discontinuation,
                         R.DischargedAlive,
                         CAST(R.AdmitDate AS DATETIME) AS AdmitDate,YEAR(R.TimeOn) AS Year,
                         CAST(R.TimeOn AS DATETIME) AS TimeOn,
                         CAST(ISNULL(R.TimeOff,
                         (SELECT TOP (1) EndTime
                          FROM ECLS.RunDetails AS RD
                          WHERE (RunId = R.RunId) AND (NOT (EndTime IS NULL))
                          ORDER BY EndTime DESC)) AS DATETIME2) AS TimeOff,
                         CAST(R.DischargeDate AS DATETIME) AS DischargeDate,
                         CAST(R.DeathDate AS DATETIME) AS DeathDate,
                         DATEDIFF(day, CAST(P.Birthdate AS DATETIME), CAST(R.TimeOn AS DATETIME)) AS Age,
                         R.CompletedDate,
                          CASE WHEN (R.CompletedBy IS NULL) OR
                         ((R.TimeOn IS NULL) OR
                         (R.TimeOff IS NULL)) OR
                         (R.CompletedBy IS NOT NULL AND ((R.TimeOn IS NULL) OR
                         (R.TimeOff IS NULL))) THEN 'false' ELSE 'true' END AS IsCompleted, 
                         dbo.ELSO_IGD_CalculateAge(DATEDIFF(day, P.Birthdate,R.TimeOn)) AS customAge,
          CASE WHEN (R.CompletedBy IS NULL) OR
                         ((R.TimeOn IS NULL) OR
                         (R.TimeOff IS NULL)) OR
                         (R.CompletedBy IS NOT NULL AND ((R.TimeOn IS NULL) OR
                         (R.TimeOff IS NULL))) THEN 'false' ELSE 'true' END AS ShowSubmitted


  FROM ECLS.Runs AS R INNER JOIN
       Registry.Patients AS P ON R.PatientId = P.PatientId INNER JOIN
       Registry.CenterPatients CP ON P.PatientId = CP.PatientId
  WHERE CP.CenterId = @CenterId 
  ORDER BY  R.TimeOn;           

END;

我使用"Update model from database"导入存储过程,目标类型为实体"RunSummary"(Kendo Grid使用它作为模型)。与模型通信的过程是:

public List<RunSummary> GetRunSummariesForPatientReportGrid(Guid? centerId)
        {
            using (var context = new ELSORegistryEntities())
            {
                return context.IGD_spPatientListReportFillGrid(centerId).ToList<RunSummary>();
            }
        }

控制器中的代码为:

public JsonResult GetRunSummaries([ELSORegistry.Helpers.CustomDataSourceRequest] DataSourceRequest request)
        {
            var center = Session["Center"] as Center;
            var centerId = center != null && center.CenterNo != 0 ? center.CenterId : (Guid?)null;
            List<RunSummary> myList = new Repository().GetRunSummariesForPatientReportGrid(centerId);

            return Json(myList.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

我的问题是在剑道网格不显示任何东西,它是空的。在浏览器中,在控制台中,我发现了错误:"ObjectContext实例已被处置,不能再用于需要连接的操作"。(我想提一下,字段ShowSubmitted是在RunSummary的模型扩展中实现的,如:

public bool ShowSubmitted
        {
            get
            {
                return this.LookForSubmitted();
            }
        }  
private bool LookForSubmitted()
        {
            bool retVal = false;
            retVal = (new Repository()).GetSubmitted(this.RunId);
            return retVal;
        }
public bool GetSubmitted(Guid? runId = null)
        {
            using (var context = new ELSORegistryEntities())
            {
                context.Configuration.ProxyCreationEnabled = false;
                RunSummary run = context.RunSummaries.FirstOrDefault<RunSummary>(p => p.RunId == runId);
                bool submitted = false;
                if (run.IsCompleted == "true")
                    {
                        submitted = true;
                    }
                    else
                    {
                        submitted = false;
                    }
                return submitted;
            }
        }

你知道怎么解决这个问题吗?提前感谢您的任何帮助。

ObjectContext实例已被处理,不能再用于需要连接错误的操作

尝试通过将以下代码片段添加到DbContext类中来禁用延迟加载。默认情况下,实体框架延迟加载数据,这意味着数据直到被请求时才加载。

public AlenanDBEntities(): base("name=AlenanDBEntities")
{
    this.Configuration.LazyLoadingEnabled = false;
}

如果你不想禁用所有实体的延迟加载,你可以通过使用virtual关键字声明一个属性来启用急切加载。不知道你的实体是什么样子,你会添加这样的东西

public class Run
{
     public virtual List<RunSummary> RunSummaries { get; set; }
}