mvc中如何自动增加ID

How increment ID automatic in mvc

最近我在 mvc 中遇到了一个问题。我的问题是关于如何增加唯一的、主要的和 int 字段的值。例如,我有一个 customerCode 作为 int,我想在保存新客户后增加它的值。我得到那个 mvc 首先检查 id,如果它等于零,然后将它递增到 max+1。但是问题来了:如果我想像Max+4那样递增,我该如何处理呢? 这是我的代码:

public ActionResult Save(Customers customer)
{
    if (!ModelState.IsValid)
    {
        var _Customer = new CreatnewCustomerViewModel()
        {
            Customer = customer,
            membershiptype = _context.membershiptype.ToList()
        };
        return View("CustomerForm", _Customer);
    }
    if (customer.CustomerID==0)
    {
        //int id = _context.customers.Max(m => m.CustomerID);
        //customer.CustomerID = id + 1;
        _context.customers.Add(customer);
    }
    else
    {
        var CustomerIndb = _context.customers.Single(c => c.CustomerID == customer.CustomerID);
            {
            CustomerIndb.Name = customer.Name;
            CustomerIndb.birthday = customer.birthday;
            CustomerIndb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
            // CustomerIndb.MembershipType = customer.MembershipTypeID;
            CustomerIndb.MembershipTypeID = customer.MembershipTypeID;
            }



    }
    _context.SaveChanges();
    return RedirectToAction("index", "Customer");
}

在 Up().

如果您对上述两个概念都不熟悉,请点击这里的链接,其中包含清晰的说明

https://forums.asp.net/t/2062551.aspx?Entity+Framework+How+to+set+a+start+value+for+an+Auto+Incremented+Column+

补充: How to set initial value for auto incremented property (DatabaseGeneratedOption.Identity)

希望对解决问题有帮助,让我知道你的状态。

谢谢

写下你的Customers模型class如下:

public class Customers
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int CustomerID { get; set; }

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

   public string Name { get; set; }

  // Other properties

}

现在生成一个新的迁移并相应地更新数据库!

现在如果要设置 Identity Increment 多于 1,然后使用 SQL Server Management Studio 转到数据库,打开 Customers table。右键单击 CustomerCode 列,然后单击 select 属性。现在将 Identity Increment 值(默认值为 1)设置为您想要的值。