我有一个具有一些CRUD功能的MVC应用程序,我注意到在创建新记录时,应该自动生成的一个字段返回0.有没有办法可以填充此字段以增加每个字段创建新记录的时间。感谢。
测试显示每当我添加记录时StoreNumber如何保持为0。
控制器:
public ActionResult Create()
{
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CustomerCompanyName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "StoreID,CustomerID,StoreName,StoreUID,StoreNumber,StoreLogo,StoreLogoPath,StoreAddress,StoreCity,StoreRegion,StoreCountry")] Store store)
{
if (ModelState.IsValid)
{
store.StoreUID = Guid.NewGuid();
db.Stores.Add(store);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "CustomerCompanyName", store.CustomerID);
return View(store);
}
商店类
public partial class Store
{
public int StoreID { get; set; }
public int CustomerID { get; set; }
public string StoreName { get; set; }
public System.Guid StoreUID { get; set; }
public int StoreNumber { get; set; }
public string StoreLogo { get; set; }
public string StoreLogoPath { get; set; }
public string StoreAddress { get; set; }
public string StoreCity { get; set; }
public string StoreRegion { get; set; }
public string StoreCountry { get; set; }
public virtual Customer Customer { get; set; }
}
答案 0 :(得分:1)
public partial class Store
{
public int StoreID { get; set; }
public int CustomerID { get; set; }
public string StoreName { get; set; }
public System.Guid StoreUID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int StoreNumber { get; set; }
public string StoreLogo { get; set; }
public string StoreLogoPath { get; set; }
public string StoreAddress { get; set; }
public string StoreCity { get; set; }
public string StoreRegion { get; set; }
public string StoreCountry { get; set; }
public virtual Customer Customer { get; set; }
}
只需将DatabaseGenerated属性用于您的字段
答案 1 :(得分:0)
CREATE TABLE [dbo].[Test1] (
[Id] INT NOT NULL IDENTITY (1, 1),
您需要具有自动增量的数据库表
答案 2 :(得分:0)
每个表只能自动生成一个标识。我假设这是StoreID字段。因此,您必须使用[DatabaseGenerated(DatabaseGeneratedOption.Identity)]标记StoreID。或者,如果列实际上是Id(int)并且已经使用[DatabaseGenerated(DatabaseGeneratedOption.Identity)]标记,那么这意味着没有其他int字段将通过SQL的内置标识功能自动更新。因此,您必须手动设置数字,因为没有任何更新。