asp.net-mvc - 如何在 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");
}
解决方案
编写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)设置为您想要的值。
推荐阅读
- python - 如何通过 Python 在一个字符串中打开一堆 .txt 文件
- string - 在两个正则表达式“|”之间提取字符串 模式
- javascript - 在javascript中使用自定义条件拆分字符串(不重复)
- assembly - 组装更改我的字符串的字符
- ios - 未找到 iOS 构建错误“RCTPackagerClient.h”文件中的 React Native Maps 集成
- ios - 迅速将 UIImage 降级到 1MB
- python - modify_instance_attribute() 只接受关键字参数
- javascript - 为什么我得到 406 不可接受的响应?
- python - django 或 gunicorn 无法读取 linux 环境变量
- python - 在 Pandas 中创建一个带有数字的新列以与具有现有数字的列分组