gpt4 book ai didi

c# - 当 IDENTITY_INSERT 设置为 OFF 时,无法为标识列插入显式值

转载 作者:行者123 更新时间:2023-11-30 19:56:00 26 4
gpt4 key购买 nike

我正在尝试设置一个复合主键,第二个键是年份。

我已经在表创建和构造函数中设置为自动生成字段,但我仍然收到此错误:

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

代码和设置的所有三个部分如下。

  [Table("Volunteer")]
public class Volunteer
{

[Key][Column(Order = 0)]
public int Id { get; set; }

[DisplayName("First Name")]
public string FirstName { get; set; }

[DisplayName("Last Name")]
public string LastName { get; set; }

[DisplayName("Team Mentored")]
public string TeamMentored { get; set; }


[Key][Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Year { get; set; }
public string TableNumber { get; set; }
public int OfficeId { get; set; }
public string Image { get; set; }


}

CREATE TABLE [dbo].[Volunteer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](255) NULL,
[LastName] [nvarchar](255) NULL,
[TeamMentored] [nvarchar](255) NULL,
[Year] [date] DEFAULT(getdate()) NOT NULL,
[TableNumber] [nvarchar](50) NULL,
[OfficeId] [int] NOT NULL,
[Image] [nvarchar](max) NULL
)


public ActionResult Create([Bind(Include = "FirstName,LastName,TeamMentored,TableNumber,OfficeId,Image")] Volunteer volunteer)
{
try
{

if (ModelState.IsValid)
{
db.Volunteers.Add(volunteer);
db.SaveChanges();

ModelState.Clear();
}

// TODO: Add insert logic here

return RedirectToAction("Index");
}
catch
{
ModelState.AddModelError("", "DB Update Failed!");
}

return View();
}

最佳答案

尝试在“Id”属性上使用属性 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]。如果那不行,是否可以发布分配代码并保存?

关于c# - 当 IDENTITY_INSERT 设置为 OFF 时,无法为标识列插入显式值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185796/

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