【发布时间】:2017-10-02 11:13:21
【问题描述】:
我有 GeneralRepository
这是代码
public class GeneralRepository
{
public IEnumerable<Site> GetSites()
{
using (TraxgoDB ctx = new TraxgoDB())
{
return ctx.Sites;
}
}
public Customer GetCustomer(int customerID, bool main = false)
{
using (TraxgoDB ctx = new TraxgoDB())
{
var customer = ctx.Customers.First(c => c.ID == customerID);
if (main) customer = (customer as SubUser)?.MainUser ?? customer;
return customer;
}
}
public Dictionary<int,int> GetCustomerIDDictionary()
{
using (TraxgoDB ctx = new TraxgoDB())
{
return ctx.Customers.ToDictionary(
c => c.ID,
c => (c as SubUser) != null ? (int) (c as SubUser).MainUserID : c.ID
);
}
}
}
在 Global.asax 中,我有这段代码使用 repo 和 repo 中的方法
private ConcurrentDictionary<string, SiteViewModel> InitializeSites()
{
var repository = new GeneralRepository();
var siteDictionary = repository.GetSites().ToDictionary(
s => s.HostName.ToLower(),
s => SiteViewModel.CreateCustomTrackerwebSite(s.HostName, s)
);
return new ConcurrentDictionary<string, SiteViewModel>(siteDictionary);
}
当我运行网站时出现此错误
操作无法完成,因为 DbContext 已被释放。
在这一行
var siteDictionary = repository.GetSites().ToDictionary
我该如何解决这个错误?
【问题讨论】:
-
嗯。似乎是的。我制作了
return ctx.Sites.ToList();,现在它运行良好@Marisa
标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4