【问题标题】:How increment ID automatic in mvc如何在 mvc 中自动增加 ID
【发布时间】:2018-09-18 18:37:57
【问题描述】:

最近我在 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-mvc asp.net-mvc-4


【解决方案1】:

如下编写你的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)设置为您想要的值。

【讨论】:

  • 如果用户运行种子并将数据用于测试和开发目的,上述解决方案是否有效。然后我们开发人员,每次运行种子时都会进入数据库并在db中手动设置Identity Increment值。我正确吗?
  • @AliEshghi 也谢谢你。请点击我答案右侧的复选图标。
  • @AliEshghi 完成! :)
  • @TanvirArjel 是的,任务完成 :))
【解决方案2】:

您可以借助 Up() 中的 DatabaseGeneratedOption.IdentitySql() 方法轻松解决该问题。

如果您对以上两个概念都不熟悉,这里是带有明确说明的链接

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)

希望能帮助解决这个问题,让我知道你的状态。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多