c# - IDENTITY_INSERT 设置为 OFF - Visual Studio

标签 c# asp.net-mvc database entity-framework visual-studio-2012

我正在尝试将值插入到本地数据库的表中。我为此使用 EntityFramework。 我的代码非常简单明了,但是当我尝试将数据插入表中时出现此错误。

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

更新: 我现在在使用以下代码时遇到此错误。

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

这是我的代码:

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);
        }
    }
}

这是我的模型:

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; }

    }
}

这是我创建表格的方式。

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)
);

如何解决此错误?任何帮助将不胜感激。

最佳答案

由于您使用的是 Entity Framework ,因此您必须使用数据模型。将表格拖放到模型中后,只需右键单击模型上的Id,然后从属性中将StoreGeneratedPattern设置为identity 并保存。保存后再次检查,它可能会解决您的问题。但是,如果您使用代码优先方法,则此方法无效。

enter image description here

关于c# - IDENTITY_INSERT 设置为 OFF - Visual Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541338/

相关文章:

c# - 一种使用独特压缩形式解压缩文本文件的更快方法

c# - 格式化日期时间错误 "Templates can be used only with field access, property access, single-dimension array index.."

jquery - 如何使用uploadify上传多个文件时传递动态Form值

php - MySQL 连接表与过滤器

用于存储年份的 MySQL 类型 : Smallint or Varchar or Date?

sql - 循环 200 万条记录并根据每行中的特定条件生成一组更新或插入的最佳性能

c# - 使用 linq 删除子对象

c# - 什么是最好的 Convert.ToString() 或只是连接一个空字符串?

c# - 如何将光标放置在屏幕的精确中心

c# - 仅为一个 Controller 和该 Controller 的操作映射路由。其他路由设置保持可操作