当IDENTITY_INSERT设置为OFF时,无法为标识列插入显式值错误

时间:2017-05-25 14:10:47

标签: c# sql-server entity-framework

尝试向表中插入值时出现此错误。 该表是使用以下脚本创建的:

    CREATE TABLE [dbo].[Audit_PatientControlledSubstanceAgreement](
    [PatientID] [bigint] NOT NULL,
    [UsersID] [bigint] NOT NULL,
    [DateAdded] [date] NOT NULL,
    [FileName] [nvarchar](500) NULL,
    [FilePath] [nvarchar](max) NULL,
    [FileType] [nvarchar](50) NULL,
    [NextScheduledDate] [date] NULL,
    [CreateDT] [datetime2](7) NULL,
    [AgreementType] [nvarchar](50) NULL,
    [Deleted] [bit] NOT NULL,
    [ID] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Audit_PatientControlledSubstanceAgreement] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

我甚至尝试将IDENTITY_INSERT更改为ON,但仍然遇到相同的错误。我使用以下代码将项目插入表格:`

    var Audit_PatientControlledSubstanceAgreement = new Audit_PatientControlledSubstanceAgreement
                            {
                                CreateDT = DateTime.Now,
                                Deleted = true,
                                AgreementType = model.AgreementType,
                                DateAdded = model.DateAdded,
                                FileName = model.FileName,
                                FilePath = model.FilePath,
                                FileType = model.FileType,
                                NextScheduledDate = model.NextScheduledDate,
                                PatientID = model.PatientID,
                                UsersID = model.UsersID
                            };

                            db.Audit_PatientControlledSubstanceAgreement.Add(Audit_PatientControlledSubstanceAgreement);
                            db.SaveChanges();

`

1 个答案:

答案 0 :(得分:2)

Id

上方添加此行
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

喜欢这个

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }