以下是在使用存储过程时如何使用带有 asp:SqlDataSource 的 MS SQL ROWVERSION (TIMESTAMP) 列来处理并发。
像这样设置你的 SqlDataSource:
<asp:SqlDataSource ID="dsRegs" runat="server" OnUpdating="dsRegs_Updating" ConnectionString="[your connstr]" InsertCommand="RegulatoryAgency_Insert" InsertCommandType="StoredProcedure" SelectCommand="RegulatoryAgency_List" SelectCommandType="StoredProcedure" UpdateCommand="RegulatoryAgency_Update" UpdateCommandType="StoredProcedure">
<InsertParameters>
<asp:Parameter Name="RegulatoryCode" Type="String" />
<asp:Parameter Name="RegulatoryName" Type="String" />
<asp:Parameter Name="RegulatoryState" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:Parameter Name="pk_RegulatoryAgency" Type="DBNull" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="pk_RegulatoryAgency" Type="Int32" />
<asp:Parameter Name="RegulatoryCode" Type="String" />
<asp:Parameter Name="RegulatoryName" Type="String" />
<asp:Parameter Name="RegulatoryState" Type="String" />
<asp:Parameter Direction="InputOutput" Name="tsModified" Type="Empty" />
</UpdateParameters>
</asp:SqlDataSource>
需要注意的重要事项是:
- 在 UpdateParameters 中,tsModified 是 TIMESTAMP 值和 Type="Empty"。
- OnUpdating 设置为 dsRegs_Updating 事件。
现在后面的代码:
/// <summary>
/// When editing for this record/row begins in the grid, we need to get the primary key from the row,
/// and then stuff the TIMESTAMP (tsModified) into a Session variable so it persists
/// </summary>
protected void gvRegs_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
int pk = (int)e.EditingKeyValue;
var db = new myDataContext();
var ra = db.RegulatoryAgency_List(pk).First();
Session["tsModified"] = ra.tsModified;
}
/// <summary>
/// Before we call the database, convert the Session var back the original Linq-to-SQL type (System.Data.Linq.Binary), then
/// convert it to a (byte) array, and update the SqlDataSource parameter with the correct value.
/// </summary>
protected void dsRegs_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
DbParameter dp = e.Command.Parameters["@tsModified"];
dp.Value = ((System.Data.Linq.Binary)Session["tsModified"]).ToArray();
}
在这个例子中,前面使用的是 DevExpress ASPxGridView,但是数据绑定和事件在其他数据绑定控件上应该是类似的。当行编辑开始时,我们从数据库中提取记录的 tsModified 值并将其放入 Session 变量中。然后 SqlDataSource 触发它的 Updating 事件,我们获取 Session 变量,将其转换回原来的格式(在我的例子中是 System.Data.Linq.Binary,因为这个例子使用的是 Linq-to-SQL),最后是最后一个技巧是您不能将 TIMESTAMP 值作为二进制、varbinary 或字节传递 - 必须作为 btye[] 发送,.ToArray() 正在处理。
使用这样的代码,我可以通过 SqlDataSource 成功地 SELECT、INSERT、UPDATE 和 DELETE,并且数据库中的 tsModified (TIMESTAMP) 值按预期递增。