我的ASP网站有时会抛出2或3个错误。这通常发生在我很快从一个页面转到另一个页面时。通常,当我给它时间时,它不会
它们都与数据库连接有关,我试图找出触发这种行为的点或什么触发此行为,特别是在发生这种情况时我无法得到确切的点/原因/场景
所以,我的数据库上下文是这样处理的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq.Mapping;
using System.Web.UI;
namespace Models
{
public partial class MainDataContext
{
[Function(Name = "NEWID", IsComposable = true)]
public Guid Random()
{ // to prove not used by our C# code...
throw new NotImplementedException();
}
private static MainDataContext _DataContext;
public static MainDataContext CurrentContext
{
get
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
_DataContext = ((FrontEndPage)page).DataContext;
}
if (_DataContext == null)
_DataContext = new MainDataContext();
return _DataContext;
}
}
}
}
这将在FrontEndPage
中使用,db
将使用using System;
using System.Web.UI;
using Models;
using Managers;
public class FrontEndPage : System.Web.UI.Page
{
protected MainDataContext db = new MainDataContext();
public OrderManager OrderManager = new OrderManager();
public void Page_PreInit(object sender, EventArgs e)
{
}
public MainDataContext DataContext
{
get
{
return db;
}
}
public MasterPage MyMaster { get; set; }
public Meta Meta { get; set; }
public String CurrentPage { get; set; }
}
成员与数据库进行通信,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Models;
public partial class Page_Default : FrontEndPage
{
protected Models.Content contactContent;
protected ShopItem shopItem;
protected void Page_Load(object sender, EventArgs e)
{
contactContent = db.Contents.FirstOrDefault(a => a.FixedRef == "contact");
}
protected void btnTest_Click(object sender, EventArgs e)
{
OrderManager.addItemToBasket(shopItem, "");
db.SubmitChanges();
Response.Redirect("/basket");
}
}
从这一点开始,我为任何我需要的页面派生任何类,例如:
The operation cannot be performed during a call to SubmitChanges
出现的一些错误是:
There is already an open DataReader associated with this Command which must be closed first.
ExecuteReader requires an open and available Connection. The connection's current state is open.
MainDataContext
所有这些都发生在我浏览页面时。我按F5并且通常它们消失,页面显示但随后它们随机返回,通常是当我快速从一个页面更改为页面时。我想这与FrontEndPage
或Page_Default
类有关,所以我只添加了这两个类的所有代码。
如果需要,我会为 <button @click="goToEvents()" class="uk-button uk-button-link">EVENTS</button>
添加更多内容,但我想知道现在是否存在创建和保留数据库连接的方式。
答案 0 :(得分:0)
private static MainDataContext _DataContext;
动臂;死亡。从来没有这样做过。永远。数据上下文:
数据上下文应仅在单个请求的持续时间内存在。
巧合的是,我刚才提到了这个确切的情况(作为一件坏事)to someone asking about bad performance due to garbage collection。