gpt4 book ai didi

c# - IDENTITY_INSERT 设置为 OFF - Visual Studio

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:34 28 4
gpt4 key购买 nike

我正在尝试将值插入到本地数据库的表中。我为此使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com