我收到以下错误:
System.ObjectDisposedException:ObjectContext实例已被处置,不能再用于需要连接的操作。
真的很有趣
1.我使用急切加载
2-跟踪显示已加载的值
3-在第一行代码中获取数据,然后在随后的几行中给出错误
模型:
public class EndedAuctionsModel{
public Auction[] Auctions { get; set; }
public int Count { get; set; }
public int PerPage = 10;
public int Page { get; set; }
}
控制器:
public ActionResult Ended(EndedAuctionsModel m)
{
m.Page = ((string)ControllerContext.RouteData.Values["id"]).PInt(1);
using(Entities db = new Entities())
{
m.Auctions = db.Auctions.Include("participations").Where(a => a.Ends < DateTime.Now).OrderByDescending(a=>a.Ends).Skip((m.Page-1)*m.PerPage).Take(m.PerPage).ToArray();
m.Count = db.Auctions.Count(a => a.Ends < DateTime.Now);
}
return View(m);
}
视图:
<div class="participated">
@for (int i = 0; i < Model.Auctions.Length; i++)
{
Participation last = Model.Auctions[i].Participations.OrderBy(p => p.Date).Last();
<div class="col-md-12 auction" style="background:#eee; margin:5px 0;padding:10px;" data-id="@Model.Auctions[i].Id">
<div class="col-md-4"><img src="~/data/pimgs/@Model.Auctions[i].AuctionImages.First().Filename" style="width:100%;border-radius:10px;" /></div>
<div class="col-md-8">
<h3>@Model.Auctions[i].Name</h3>
<div><i class="fa fa-money big-blue"></i>قیمت شروع مزایده: <strong>@Model.Auctions[i].BasePrice.Value.ToString("N0")</strong></div>
@{ string username = last.GetUserName(); if (username == null) { username = "-"; } }
<div><i class="fa fa-gavel big-blue"></i>برنده مزائده: <strong class="last-user"><a href="/Home/Profiles/@username">@username</a></strong></div>
<div><i class="fa fa-user big-blue"></i>قیمت نهایی: <strong class="last-price">@((Model.Auctions[i].BasePrice + Model.Auctions[i].Participations.Count * Model.Auctions[i].StepPrice).Value.ToString("N0"))</strong></div>
</div>
</div>
}
</div>
错误在视图
data-id="@Model.Auctions[i].Id"
的第5行最佳答案
您的视图包括(在<img>
标记中)
@Model.Auctions[i].AuctionImages.First().Filename
但您的查询中不包含
AuctionImages
。更改为m.Auctions = db.Auctions.Include("participations").Include("AuctionImages").Where(....
关于c# - ObjectDisposedException而实际上不需要连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41111500/