表“tblCustomer”没有标识属性。无法执行SET操作

问题描述 投票:0回答:1

当我尝试在 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"/>

            }
c# entity-framework
1个回答
0
投票

假设您的表 tblCustomer 有一个标识列,并假设您正在使用符号配置映射,请为标识属性指定 DatabaseGenerated

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

如果 yout 表上没有标识列,请将其设置为 None

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx

您能否提供有关您的表和 EF 映射的更多详细信息?

© www.soinside.com 2019 - 2024. All rights reserved.