开发者

ObjectContext instance has been disposed while binding [duplicate]

This question already has answers here: Solving "开发者_运维知识库;The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException (8 answers) Closed 5 years ago.

This is my code:

public class JobsRepository:BaseNewsletterRepository
{
   public IEnumerable<Job> GetJobs()
   {
        var jobs = Newsletterctx.Jobs.Include("Info").OrderBy(o => o.JobID);             
        return jobs.AsEnumerable();
   }
}

public class BusinessNewsletter
{
   public static IEnumerable<Job> GetJobs()
   {      
        using (JobsRepository jobsRepository = new JobsRepository())
        {
            return  jobsRepository.GetJobs();
        }    
    }
}    

rptJobs.DataSource = BusinessNewsletter.GetJobs();
rptJobs.DataBind();

When I try to bind I get error:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Is the only solution, to cast and return List in BusinessNewsletter class?

public static IList<Job> GetJobs()
{
    IList<Job> job;
    using (JobsRepository jobsRepository = new JobsRepository())
    {
        job = jobsRepository.GetJobs().ToList();
    }
    return job;
}

Another related question:

How can I retrieve and bind data to a repeater without specifying a specific type (List<type> or IEnumerable<type> )

I need it in case where I return specific object like this:

var specificJob = from job in Newsletterctx.Jobs.Include("Info")
                  select new
                  {
                      ID = job.JobID,
                      EmailId = job.Info.PreparedEmailID
                  };

I must create specific class just for that object?


Yes, you will have to convert to some in-memory collection before returning. The problem is that the returned result sequence is lazily evaluated, so no attempt is made to query the database until the datasource tries to enumerate the results. At this point the ObjectContext has already been disposed.

For your second question, you should create your own classes since you cannot return anonymous types from the methods that declare them.


The using clause is disposing your ObjectContext before the View is able to use it. The solution would be to remove the using clause and change your code as follows:

  JobsRepository jobsRepository = new JobsRepository();
  return  jobsRepository.GetJobs();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜