同时结合ObjectContext的实例已被释放已被、实例、ObjectContext

2023-09-04 22:33:13 作者:劣性{玩家}

这是我的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:

的ObjectContext的实例已被释放,并可以不再被用于需要连接的操作。

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

时的唯一解决方案,投在BusinessNewsletter类返回列表?

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

另一个相关的问题:的

我怎么能检索和数据绑定到一个中继器,而无需指定一个特定的类型(名单,其中,型&GT; 的IEnumerable&LT;类型&GT; ) 我需要它的情况下,我返回特定的对象是这样的:

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?

推荐答案

是的,你将不得不返回之前转换为一些在内存中的集合。的问题是,返回的结果序列被懒惰地评估,因此不尝试,直到数据源试图枚举结果来查询数据库。此时的ObjectContext 已被释放。

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.

 
精彩推荐