使用转发器时,你会在每个itemdatabound上声明一个新的datacontext吗?

时间:2009-08-27 13:09:39

标签: asp.net linq-to-sql

这感觉不对

Private Sub drop_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles iqty.ItemDataBound
    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
        Dim row As allowanceQtyQuery = CType(e.Item.DataItem, allowanceQtyQuery)

        Dim unit = CType(e.Item.FindControl("Unit"), DropDownList)
        Using db As New myContext
            Dim u = db.getAllUnit(True)
            unit.DataSource = u
            unit.DataTextField = "descen"
            unit.DataValueField = "unitid"
            unit.DataBind()
        End Using
        unit.Text = row.Unit
    End If
End Sub

因为如果我说1000个项目,它将声明1000x datacontext

你会怎么处理这个?

创建此项以便能够删除“使用db”部分

Public ReadOnly Property listOfUnit() As List(Of Unit)
    Get
        If HttpContext.Current.Cache("unit") Is Nothing Then
            Using db As New ODSTS
                HttpContext.Current.Cache.Insert("unit", db.getAllUnit(True).ToList, Nothing, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5))
            End Using
        End If
        Return CType(HttpContext.Current.Cache("unit"), List(Of Unit))
    End Get
End Property

2 个答案:

答案 0 :(得分:1)

将数据库中的结果集作为DataTable,List或类成员变量中的任何内容进行缓存,并将每个下拉列表绑定,这样一次只能命中DB。

答案 1 :(得分:1)

正如我所看到的那样,你的datacontext并没有做任何事情,所以为什么不这样做 将它缓存在一个字段中并用于你的方法?

您可以执行以下操作:

Private Sub drop_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles iqty.ItemDataBound
    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
        Dim row As allowanceQtyQuery = CType(e.Item.DataItem, allowanceQtyQuery)
        Dim unit = CType(e.Item.FindControl("Unit"), DropDownList)
            unit.DataSource = getDataContextPriv.getAllUnit(True)
            unit.DataTextField = "descen"
            unit.DataValueField = "unitid"
            unit.DataBind()
        unit.Text = row.Unit
    End If
End Sub

Protected Sub Page_Unload(ByVal Sender as Object, ByVal e as EventArgs)
    _myContext.Dispose()
End Sub

Private _myContext as DataContext
Private Property getDataContextPriv() As DataContext
        Get
            If(_myContext is Nothing) Then
                _myContext = new myContext()
            End If
            return _myContext
        End Get
End Property