【发布时间】: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");
}
【问题讨论】:
-
让数据库为您完成,而不是代码。使用
identity列并使用DatabaseGeneratedOption.Identity在您的实体映射中指定它。 -
@Igor 你能指导我更多吗?我正在使用 sql server ,如何使用身份和DatabaseGeneratedOption.Identity 。我应该在哪里使用它们?
-
感谢亲爱的@Igor,我阅读了该链接,但我无法获得。我会研究更多...