首页 > 解决方案 > 如何在 mvc 中自动增加 ID

问题描述

最近我在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");
}

标签: asp.net-mvcasp.net-mvc-4

解决方案


编写Customers模型类如下:

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表。右键单击CustomerCode列,然后选择属性。现在将Identity Increment值(默认值为 1)设置为您想要的值。


推荐阅读