现有数据库标识列MVC 4

时间:2013-05-13 14:35:33

标签: asp.net-mvc-4

我正在使用现有数据库来创建项目报告系统。我想要主键,这是项目表的项目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; }    

1 个答案:

答案 0 :(得分:0)

只需从Razor视图中排除ID字段即可。 (除非您使用EditorForModel,否则自我解释,在这种情况下,您需要修改ID字段的Display注释,以便Razor引擎知道将其从视图中排除。)< / p>

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

相关问题