我正在尝试对DB进行大容量插入,我之前的尝试是使用dapper进行大容量嵌入,但这太可怕了,所以我尝试使用干净的ADO.NET接近
I生成数据表并从项目列表中填充:
using (SqlConnection cn = new SqlConnection(VoucherConnectionManager.connectionString))
{
cn.Open();
var cmd = new SqlCommand("SET FMTONLY ON; SELECT * FROM Voucher; SET FMTONLY OFF;", cn);
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
foreach (var itm in voucherList)
{
DataRow row = dt.NewRow();
row["VoucherUid"] = itm.Uid;
row["ClientUid"] = itm.ClientUid;
row["BatchUid"] = itm.BatchUid;
row["CardNo"] = itm.CardNo;
row["Origin"] = itm.Origin;
row["VoucherCreateDate"] = itm.VoucherCreateDate;
row["State"] = itm.State;
//row["LastTimeStamp"] = DateTime.Now;
dt.Rows.Add(row);
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(cn))
{
bulkCopy.DestinationTableName = "dbo.Voucher";
bulkCopy.WriteToServer(dt);
}
cn.Dispose();
}
这里的问题是,我得到以下错误:
An unhandled exception of type 'System.Data.NoNullAllowedException' occurred in MasterRepositorys.dll Additional information: Column 'LastTimeStamp' does not allow nulls.
LastTimeStamp是一个时间戳列,为什么不自动生成呢?我做错了什么?
编辑表DEF:
CREATE TABLE [dbo].[Voucher](
[VoucherUid] [uniqueidentifier] NOT NULL,
[ClientUid] [uniqueidentifier] NOT NULL,
[BatchUid] [uniqueidentifier] NOT NULL,
[CardNo] [nvarchar](13) NOT NULL,
[CycleUid] [uniqueidentifier] NULL,
[CycleCreateDate] [datetime] NULL,
[VoucherCreateDate] [datetime] NOT NULL,
[LastTimeStamp] [timestamp] NOT NULL,
[Type] [int] NULL,
[Origin] [int] NOT NULL,
[OrderRef] [nvarchar](36) NULL,
[State] [int] NOT NULL,
CONSTRAINT [PK_Voucher] PRIMARY KEY CLUSTERED
(
[VoucherUid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
列"LastTimeStamp"是DataTable的一部分,因此需要一个值。它是DataTable的一部分,因为您从表中选择了所有行和列
var cmd = new SqlCommand("SET FMTONLY ON; SELECT * FROM Voucher; SET FMTONLY OFF;", cn);
...
dt.Load(cmd.ExecuteReader());
在大容量插入之前,是否需要将所有值加载到DataTable?我想不会。因此,您可以通过避免select和dt.Load
来解决这个问题,而是只将要大容量插入的列添加到表中,如下所示:
table.Columns.Add("VoucherUid", typeof (...));
或者,我认为您仍然可以使用select,但只选择要插入的列。
时间戳数据类型的sql表中的列是自动生成的,不要在其中显式插入值,只要在表中插入记录,就会用当前时间戳填充
将您的代码更改为以下内容,说明LastTimeStamp
是TimeStamp
类型,否则您实际上是在说LastTimeStamp is null
,因此会得到错误。
foreach (var itm in voucherList)
{
DataRow row = dt.NewRow();
row["VoucherUid"] = itm.Uid;
row["ClientUid"] = itm.ClientUid;
row["BatchUid"] = itm.BatchUid;
row["CardNo"] = itm.CardNo;
row["Origin"] = itm.Origin;
row["VoucherCreateDate"] = itm.VoucherCreateDate;
row["State"] = itm.State;
row["LastTimeStamp"] = SqlDbType.Timestamp; //Here
dt.Rows.Add(row);
}