我试图使用Linq将记录插入到表中,但是获得可怕的无法添加具有已使用错误的键的实体错误
'If the same data exists for the same patient in a record less that 21 days old then drop it Dim RecordLookup As Integer = 0 RecordLookup = (From rc In CDEvodb.RISKCHANGEs _ Where rc.NHI = tmpNHI And _ rc.RECDATE > Date.Now.AddDays(-21) And _ rc.BPSYS = Convert.ToDecimal(Drow.Item("BPSYS")) And _ rc.CHOL = Convert.ToDecimal(Drow.Item("CHOL")) And _ rc.HDL = Convert.ToDecimal(Drow.Item("HDL"))).Count() If (RecordLookup = 0) Then Dim riskchange As New RISKCHANGE riskchange.NHI = Drow.Item("NHI") riskchange.RECDATE = Date.Now.Date() riskchange.RISK = CalculatedRisk riskchange.BPSYS = Drow.Item("BPSYS") riskchange.CHOL = Drow.Item("CHOL") riskchange.HDL = Drow.Item("HDL") Try CDEvodb.RISKCHANGEs.InsertOnSubmit(riskchange) Catch ex As Exception myLogging.OutputError("<" & DateTime.Now.ToString & "> " & "Error - creating risk change record in dataset for patient " & Drow.Item("NHI").ToString() & " - " & ex.Message) End Try End If
基本上我在表上查找不到21天的匹配记录(不包括Identity字段).如果我找不到一个,我创建一个行的实例并设置插入它.
SubmitChanges函数调用几行.
Drow是来自之前使用SQLClient连接填充的数据集的DataRow(原因是我尚未完全转换为Linq,现在只是执行新功能).
提前干杯.
这是表的创建脚本:
USE [CDEvolution]
走
/******对象:表[dbo].[RISKCHANGES]脚本日期:05/13/2009 14:40:15******/
SET ANSI_NULLS ON
走
SET QUOTED_IDENTIFIER ON
走
SET ANSI_PADDING ON
走
CREATE TABLE [dbo].[RISKCHANGES](
[NHI] [varchar](7) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [RECDATE] [datetime] NOT NULL, [RISK] [numeric](15, 0) NOT NULL, [BPSYS] [numeric](15, 0) NOT NULL, [CHOL] [numeric](15, 1) NOT NULL, [HDL] [numeric](15, 1) NOT NULL, [POSTED] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL, [IDENTITY] [uniqueidentifier] NOT NULL CONSTRAINT [DF_RISKCHANGES_IDENTITY]
DEFAULT(newid()),
CONSTRAINT [PK_RISKCHANGES] PRIMARY KEY CLUSTERED
(
[IDENTITY] ASC
)WITH(PAD_INDEX = OFF,IGNORE_DUP_KEY = OFF)ON [PRIMARY]
)[主要]
走
SET ANSI_PADDING OFF
如果更新DBML,请将此(IsDbGenerated ="true")添加到PK成员:
它将让SQL分配默认值(newid()).
否则它会发送未经过授权的guid('00000000-0000-0000-0000-000000000000'),这就是我所知道的问题.
您的另一个选择可能是扩展部分类并初始化OnCreated()事件中的GUID(它不使用列的newid()默认值,但确实解决了问题:
partial class RISKCHANGE { partial void OnCreated() { _IDENTITY = Guid.NewGuid(); } }
请注意,对于现有实体(由查询填充),当处理OnLoaded()时,将使用正确的值覆盖此值.