0

我正在使用现有数据库来创建项目报告系统。我希望主键,即项目表的项目 id 值被自动创建并且它没有设置新值,因为我必须输入 Id,但我不希望用户这样做。谁能帮我解决这个问题?

帕特里克

控制器 ` // // GET: /Project/Create

    public ActionResult Create()
    {
        ViewBag.Status = new SelectList(db.pjt_Statuses, "pjt_Status_ID", "StatusName");
        ViewBag.SubCategoryID = new SelectList(db.pjt_SubCategories, "pjt_SubCat_ID", "SubCatName");
        return View();
    }

    //
    // POST: /Project/Create

    [HttpPost]
    public ActionResult Create(pjt_Projects pjt_projects)
    {
        if (ModelState.IsValid)
        {
            pjt_projects.CreationDate = DateTime.Now;
            db.pjt_Projects.Add(pjt_projects);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.Status = new SelectList(db.pjt_Statuses, "pjt_Status_ID", "StatusName", pjt_projects.Status);
        ViewBag.SubCategoryID = new SelectList(db.pjt_SubCategories, "pjt_SubCat_ID", "SubCatName", pjt_projects.SubCategoryID);
        return View(pjt_projects);
    }`

数据库表脚本

`CREATE TABLE [dbo].[pjt_Projects](
[Pjt_Id] [int] IDENTITY(1,1) NOT NULL,
[ProjectName] [nchar](100) NULL,
[Status] [int] NULL,
[Start_Date] [date] NULL,
[Estimated_End_Date] [date] NULL,
[Documents] [nvarchar](max) NULL,
[Notes] [nvarchar](max) NULL,
[Budget] [smallmoney] NULL,
[Current_Spending] [smallmoney] NULL,
[ProjectOwner] [nvarchar](50) NULL,
[Active] [bit] NULL,
[Actual_End_date] [date] NULL,
[CreationDate] [date] NULL,
[CreatedByEmpNo] [nchar](10) NULL,
[UpdateDate] [date] NULL,
[UpdatedByEmpNo] [nchar](10) NULL,
[SubCategoryID] [int] NULL,`


**Generate Context Db Code**
    public int Pjt_Id { get; set; }
    public string ProjectName { get; set; }
    public Nullable<int> Status { get; set; }
    public Nullable<System.DateTime> Start_Date { get; set; }
    public Nullable<System.DateTime> Estimated_End_Date { get; set; }
    public string Documents { get; set; }
    public string Notes { get; set; }
    public Nullable<decimal> Budget { get; set; }
    public Nullable<decimal> Current_Spending { get; set; }
    public string ProjectOwner { get; set; }
    public Nullable<bool> Active { get; set; }
    public Nullable<System.DateTime> Actual_End_date { get; set; }
    public Nullable<System.DateTime> CreationDate { get; set; }
    public string CreatedByEmpNo { get; set; }
    public Nullable<System.DateTime> UpdateDate { get; set; }
    public string UpdatedByEmpNo { get; set; }
    public Nullable<int> SubCategoryID { get; set; }    
4

1 回答 1

0

只需从 Razor 视图中排除 ID 字段。(不言自明,除非您使用EditorForModel,在这种情况下,您需要修改DisplayID 字段的注释,以便 Razor 引擎知道将其从视图中排除。)

一旦被排除,它的值将不会被发送回服务器。这样在 MVC 控制器中创建时将获得默认值;并且数据库将自动生成新 ID。

于 2013-05-14T20:54:09.777 回答