新增实体时,为什么主键ID是0?
实体类代码如下:
- C# code
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; } }}
前台代码如下:
- HTML code
@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>}
因为新增时实体的ID是0,导致验证无法通过。
在另外个项目中查看了一下,正常情况下,第一张图中的DeptID应该自动获取1个自增ID值。
求解~~谢谢
[解决办法]
你用的什么框架,网上搜索了一下,只找到yawetag-lib这个库里包含了EntityRepository类,不知道你用的是不是这个。
自增字段的值需要在插入数据库以后才能生成,也就是要调用了Insert方法并提交数据库以后才有值,所以你那总写法肯定是有问题的。
最简单的是不要验证ID字段或者给他赋一个任意的有效值
[解决办法]
主键自增的话,insert语句里说不对其进行赋值的。
用linq也一样。
但因为是Int类型,所以在调试时看到的值即为0
[解决办法]
你自己写的orm框架,生成的语句当然要自己赋值了
[解决办法]
DeptID 是 Int 默认就是0
另外DeptID在数据库是自增长的,所以无需赋值,插入数据库的时候,DeptId会根据表内数据产生值。
所以 你这边不需要管DeptId,更不需要验证DeptId