新增实体时,为什么主键ID是0?
实体类代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ComponentModel.DataAnnotations;namespace DataEntity{ [Table("Hr_Department")] public class Department { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int DeptID { get; set; } [Display(Name = "部门名称")] [StringLength(100)] [Required(ErrorMessage = "部门名称不能为空")] public string DeptName { get; set; } [Display(Name = "上级部门")] public int? ParentID { get; set; } [Display(Name = "部门编号")] [StringLength(100)] [Required(ErrorMessage = "部门编号不能为空")] public string DeptCode { get; set; } [Display(Name = "电话")] [StringLength(100)] public string DeptPhone { get; set; } [Display(Name = "传真")] [StringLength(100)] public string DeptFax { get; set; } }}
@using (Html.BeginForm("", "", FormMethod.Post, new { id = "deptForm" })){ @Html.ValidationSummary(true) <fieldset> <legend id="legendText">编辑部门</legend> <div id="keyField"> @Html.HiddenFor(model => model.DeptID) </div> <div class="editor-label"> @Html.LabelFor(model => model.DeptName) </div> <div class="editor-field"> @Html.EditorFor(model => model.DeptName) @Html.ValidationMessageFor(model => model.DeptName) </div> <div class="editor-label"> @Html.LabelFor(model => model.DeptCode) </div> <div class="editor-field"> @Html.EditorFor(model => model.DeptCode) @Html.ValidationMessageFor(model => model.DeptCode) </div> <div class="editor-label"> @Html.LabelFor(model => model.DeptPhone) </div> <div class="editor-field"> @Html.EditorFor(model => model.DeptPhone) @Html.ValidationMessageFor(model => model.DeptPhone) </div> <div class="editor-label"> @Html.LabelFor(model => model.DeptFax) </div> <div class="editor-field"> @Html.EditorFor(model => model.DeptFax) @Html.ValidationMessageFor(model => model.DeptFax) </div> <div class="editor-label"> @Html.LabelFor(model => model.ParentID) </div> <div class="editor-field"> <input id="ParentID" name="ParentID" value="@ParentID" required="true" /> </div> <p> <input type="button" value="保存" onclick="saveDeptForm()" /> </p> </fieldset>}
[解决办法]
你自己写的orm框架,生成的语句当然要自己赋值了
[解决办法]
DeptID 是 Int 默认就是0
另外DeptID在数据库是自增长的,所以无需赋值,插入数据库的时候,DeptId会根据表内数据产生值。
所以 你这边不需要管DeptId,更不需要验证DeptId