简体   繁体   English

IDENTITY_INSERT 设置为 OFF - Visual Studio

[英]IDENTITY_INSERT is set to OFF - Visual Studio

I'm trying to insert values into a table in a local database.我正在尝试将值插入到本地数据库中的表中。 I'm using the EntityFramework for this.我为此使用了 EntityFramework。 My code is pretty simple and straight forward, however I'm getting this error, when I try to insert data into the table.我的代码非常简单直接,但是当我尝试将数据插入表中时出现此错误。

Cannot insert explicit value for identity column in table 'PUserDataTable' when IDENTITY_INSERT is set to OFF.

Update: I'm getting this error with the below code now.更新:我现在使用以下代码收到此错误。

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Here's my code:这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SampleDatabase.Controllers
{
    public class PUserDataTableController : Controller
    {
        PUserDataTableContext db = new PUserDataTableContext();

        public ActionResult Index()
        {
            return View(db.PUserDataTables.ToList());
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]

        public ActionResult Create(PUserDataTable userdata)
        {
           if(ModelState.IsValid)
           {
            db.PUserDataTables.Add(userdata);
            try
            {
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }

           }
            return View(userdata);
        }
    }
}

Here is my Model:这是我的 Model:

namespace SampleDatabase
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations.Schema;

    public partial class PUserDataTable
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Nullable<int> Id { get; set; }
        public string DeviceID { get; set; }
        public string TimeSpent { get; set; }
        public Nullable<int> NumPages { get; set; }
        public string History { get; set; }
        public string FinalPage { get; set; }

    }
}

Here is how I create my table.这是我创建表的方式。

CREATE TABLE [dbo].[PUserDataTable] (
    [Id]        INT           IDENTITY (1, 1) NOT NULL,
    [DeviceID]  VARCHAR (50)  NULL,
    [TimeSpent] VARCHAR (50)  NULL,
    [NumPages]  INT           NULL,
    [History]   VARCHAR (MAX) NULL,
    [FinalPage] VARCHAR (50)  NULL,
    CONSTRAINT [PK_PUserDataTable] PRIMARY KEY CLUSTERED ([Id] ASC)
);

How do I resolve this error?如何解决此错误? Any help will be appreciated.任何帮助将不胜感激。

Since you are using Entity Framework you must be using a data model.由于您使用的是实体框架,因此您必须使用数据模型。 Once you drag and drop table into model just Right Click on the Id filed on model and from the properties set StoreGeneratedPattern into identity and save.将表拖放到模型中后,只需右键单击模型上的Id ,然后从属性中将StoreGeneratedPattern设置为标识并保存。 Check again after save and it might fix your problem.保存后再次检查,它可能会解决您的问题。 But if you are using code first approach this method not valid.但是,如果您使用代码优先方法,则此方法无效。

在此处输入图像描述

That looks like Sql Server, not MySql (MySql has AUTO_GENERATED columns, Sql Server has Identity ).这看起来像 Sql Server,而不是 MySql(MySql 有AUTO_GENERATED列,Sql Server 有Identity )。

Either way, your Entity PK property PUserDataTable.ID should be marked with :无论哪种方式,您的实体 PK 属性PUserDataTable.ID都应标记为:

public class PUserDataTable
{
   [DatabaseGenerated(DatabaseGenerationOption.Identity)]
   public int ID {get; set;}

, or if you are using the fluent api, use ,或者如果您使用的是 fluent api,请使用

.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 

This will stop EF trying to insert the column.这将阻止 EF 尝试插入该列。

Assuming your PUserDataTable class has an internal structure like this:假设您的 PUserDataTable 类具有这样的内部结构:

public class PUserDataTable {
   public int Id {get;set;}
   //other properties
}

you should add this attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)] and that should solve the problem.您应该添加此属性[DatabaseGenerated(DatabaseGeneratedOption.Identity)]应该可以解决问题。

This attribute warns EF that the database is already generating a value for this property/column and no need to worry about that, otherwise EF seems to generate a value for the fields with primitive types.此属性警告 EF 数据库已经在为此属性/列生成值,无需担心,否则 EF 似乎会为具有原始类型的字段生成值。 In int's case it's 0.在 int 的情况下,它是 0。

In my case: My program uploads many files.就我而言:我的程序上传了许多文件。 Each file was processed and noted in a table on a database.每个文件都经过处理并记录在数据库的表中。 So I used a loop for each file.所以我为每个文件使用了一个循环。 My mistake was that I didn't reinstanciate the table inside the loop.我的错误是我没有在循环内重新实例化表格。 After moving var table = new Table();移动后var table = new Table(); inside the loop the failure disappeared.在循环内部,故障消失了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IDENTITY_INSERT设置为OFF - IDENTITY_INSERT is set to OFF IDENTITY_INSERT 设置为 OFF 的问题? :-/ - Problems with IDENTITY_INSERT Set to OFF? :-/ IDENTITY_INSERT设置为OFF时,无法手动为标识插入ID实体插入显式值 - Cannot insert explicit value for identity insert ID manually entity when IDENTITY_INSERT is set to OFF 实体框架:当IDENTITY_INSERT设置为OFF时,无法为表&#39;[table]&#39;中的标识列插入显式值 - Entity Framework: Cannot insert explicit value for identity column in table '[table]' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法为表&#39;ActivityInstances中的标识列插入显式值 - Cannot insert explicit value for identity column in table 'ActivityInstances' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法为标识列插入显式值 - Cannot insert explicit value for identity column when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Recipe&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法在表&#39;MyTableName&#39;中为标识列插入显式值 - Cannot insert explicit value for identity column in table 'MyTableName' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;AspNetUsers&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,无法在表&#39;candidatedetails&#39;中为identity列插入显式值 - Cannot insert explicit value for identity column in table 'candidatedetails' when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM