在我尝试在SQL DATAMANAGEMENT STUDIO中将identity_insert设置为ON时发生。
最糟糕的是我不知道为什么要处理这个值,我甚至不确定以下代码是否比本地内存中的数据库副本更多。
当调试到达SaveChanges行时,我之前收到此消息: “当IDENTITY_INSERT设置为OFF时,无法在表'tblCustomer'中为标识列插入显式值”
` public ActionResult Submit(
Customer obj) //validation runs
{
if (ModelState.IsValid)
{
CustomerDal Dal = new CustomerDal();
Dal.Customer.Add(obj); //in memory
Dal.SaveChanges(); //physical commit
return View("Customer", obj);
}
else
{
return View("EnterCustomer", obj);
}
}`
public class Customer
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.none)]
public string CustomerCode { get; set; }
[Required]
[StringLength(10)]
[RegularExpression("^[A-Z]{7,7}$")]
public string CustomerName { get; set; }
}
public class CustomerDal : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Customer>().ToTable("tblCustomer");
}
public DbSet<Customer> Customer { get; set; }
}
CREATE TABLE [dbo].[tblCustomer](
[CustomerCode] [varchar](50) NOT NULL,
[CustomerName] [varchar](50) NULL,
CONSTRAINT [PK_tblCustomer] PRIMARY KEY CLUSTERED
(
[CustomerCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
) ON [PRIMARY]
@using (Html.BeginForm("Submit", "Customer", FormMethod.Post))
{
<i>Customer Name : </i> @Html.TextBoxFor(m => m.CustomerName)
<br>
@Html.ValidationMessageFor(x => x.CustomerName)
<br>
<i>Customer Code : </i> @Html.TextBoxFor(m => m.CustomerCode)
<br>
@Html.ValidationMessageFor(x => x.CustomerCode)
<br>
<input id = "Submit1" type = "submit" value = "submit"/>
}
答案 0 :(得分:0)
假设您的表 tblCustomer 有一个标识列,并假设您使用标记配置映射,请为标识属性指定 DatabaseGenerated :
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
如果您在yout表上没有标识列,请将其设置为无。
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx
您能否提供有关表格和EF映射的更多详细信息?