如果我有一个包含 RowVersion 列的 SQLDataRecord,如下面的代码所示。我总是收到 SQL Server 错误 8052
传入的表格数据流 (TDS) 远程过程调用 (RPC) 协议流不正确。表值参数 %d ("%.*ls"),行 %I64d,列 %d:数据类型 0x%02X(用户定义的表类型)时间戳列需要为默认值。
我是否将 RowVersion 值设置为 null 或一个值。
我希望能够将现有记录的 RowVersion 值和新记录的空值从 ADO.NET 发送到存储过程,这样我就可以在合并记录时使用随机并发检查。
如何才能做到这一点?
namespace MyApplication.DataAccess
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.SqlServer.Server;
public interface IRowVersionRecord
{
Byte[] RowVersionValue { get; set; }
Int32? Somevalue { get; set; }
}
public class RowVersionRecordBase : IRowVersionRecord
{
public Byte[] RowVersionValue { get; set; }
public Int32? Somevalue { get; set; }
public static IEnumerable<SqlDataRecord> CreateSqlDataRecordEnumerable(IEnumerable<IRowVersionRecord> dataTransferObjects)
{
var sqlMetaData = new SqlMetaData[]
{ new SqlMetaData("RowVersionValue", SqlDbType.Timestamp),
new SqlMetaData("somevalue", SqlDbType.Int)
};
var record = new SqlDataRecord(sqlMetaData);
foreach (var dto in dataTransferObjects)
{
record.SetValue(0, dto.RowVersionValue);
record.SetValue(1, dto.Somevalue);
yield return record;
}
}
}
public partial class RowVersionRecord : RowVersionRecordBase
{
}
}
namespace MyApplication.DataAccess
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
public abstract class RowVersionDAOBase : DAO
{
public virtual void Upsert(IEnumerable<RowVersionRecord> values)
{
using (var connection = Connection)
{
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "RowVersion_Upsert";
((SqlCommand)command).Parameters.Add("@values", SqlDbType.Structured).Value =
(object)RowVersionRecordBase.CreateSqlDataRecordEnumerable(values) ?? (object)DBNull.Value;
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SequentialAccess))
{
while (reader.NextResult())
{
///.....
}
}
}
}
}
}
public partial class RowVersionDAO : RowVersionDAOBase
{
}
}
//Test code snip
[TestMethod]
public void RowVersionTVPTest()
{
RowVersionRecord record = new RowVersionRecord();
record.Somevalue = 1;
List<RowVersionRecord> records = new List<RowVersionRecord>()
{
record
};
using (RowVersionDAO dao = new RowVersionDAO())
{
dao.Upsert(records);
}
}