[英]Cannot insert explicit value for identity column when IDENTITY_INSERT is set to OFF
I'm attempting to set up a composite primary key with the second key being the year. 我正在尝试设置一个复合主键,第二个键是年份。
I've set both in the table creation and the constructor to auto generate the field but I still get this error: 我已经在表创建和构造函数中设置了自动生成字段,但我仍然收到此错误:
Cannot insert explicit value for identity column in table Volunteer when IDENTITY_INSERT is set to OFF.
当IDENTITY_INSERT设置为OFF时,无法在表Volunteer中为标识列插入显式值。
All three parts to the code and setup are below. 代码和设置的所有三个部分都在下面。
[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();
}
Try using the attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)] on "Id" property. 尝试在“Id”属性上使用属性[DatabaseGenerated(DatabaseGeneratedOption.Identity)]。 If that doesn't do it, is it possible to post the code of assignment and save?
如果不这样做,是否可以发布分配代码并保存?
Your attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
tells Entity Framework (and SQL Server) that the property will be auto-generated by the database using an auto-incrementing value. 您的属性
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
告诉实体框架(和SQL Server)该属性将由数据库使用自动递增值自动生成。 Therefore, you can not provide it a value. 因此,您无法为其提供值。
If it will work at all, you will have to move it to the Id
property. 如果它可以工作,你将不得不将它移动到
Id
属性。 It would probably work, but I can't say for certain as I haven't worked with a composite Key before. 它可能会工作,但我不能肯定,因为我之前没有使用过复合键。
If you are still getting the error, then it is because the database has been created with the Year
column set as int identity(1,1)
. 如果仍然出现错误,那么这是因为已创建数据库时将
Year
列设置为int identity(1,1)
。 Either manually edit the database, or delete it and recreate it with a new migration. 手动编辑数据库,或删除它并使用新的迁移重新创建它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.