Reputation: 11059
I am developing an application with SQL CE and EF Poco 4.
The following code
Context
public class Context : DbContext
{
public DbSet<BoletimSemanal> BoletinsSemanais { get; set; }
public Context()
: base("name=DefaultConnection")
{
}
}
Model
public class BoletimSemanal
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public int Week { get; set; }
public int Year { get; set; }
}
Controller
public ActionResult Index()
{
IQueryable<BoletimSemanal> boletins;
using (var db = new Context())
{
var calInfo = DateTimeFormatInfo.CurrentInfo;
var week = calInfo.Calendar.GetWeekOfYear(DateTime.Now, calInfo.CalendarWeekRule, calInfo.FirstDayOfWeek);
boletins = (from boletim in db.BoletinsSemanais
where boletim.Week == week
&& boletim.Year == DateTime.Now.Year
select boletim);
}
return View(boletins.DefaultIfEmpty());
}
Web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|Data.sdf;" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
View
@model IEnumerable<SextaIgreja.Web.Models.BoletimSemanal>
@{
ViewBag.Title = "Downloads";
}
<div id="boletim-semanal" class="column last">
<p class="title">Boletim Semanal
@if (Request.IsAuthenticated)
{
@Html.ActionLink("+", "Create", "Downloads", new { @class="add" })
}
</p>
<div class="content border">
<p>Content</p>
<ul>
@foreach (var item in Model)
{
<li>@item.Name</li>
}
</ul>
</div>
</div>
the following error occurs in foreach:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Source Error:
Upvotes: 0
Views: 581
Reputation: 1705
Try to pass a IList instead the IQueryable.
You can do that adding a .ToList() to the end of the linq query:
boletins = (from boletim in db.BoletinsSemanais
where boletim.Week == week
&& boletim.Year == DateTime.Now.Year
select boletim).ToList();
Upvotes: 1
Reputation: 9114
From your code, I see that you are using IQueryable. This means that when the view iterates that IQueryable, ObjectContext is already disposed, so you can't access the database. Note that when you are using IQueryable data from db is fetched when you are iterating over it (throug foreach in your example).
IList<BoletimSemanal> boletins;
boletins = (from boletim in db.BoletinsSemanais
where boletim.Week == week
&& boletim.Year == DateTime.Now.Year
select boletim).ToList();
Try this and it should work.
Upvotes: 1