即使是自定义类,Autogentrated Entity模型也始终如一

时间:2015-09-03 11:40:06

标签: asp.net-mvc

我正在使用自动生成的实体模型类,而不是使用带元数据的分部类将验证放在自动遗传类上,如下所示。

public class tblDepartmentCustom
    {

        [Key]
        public int DepartmentId { get; set; }
        [Required(ErrorMessage = "Department name is required")]
        public string DepartmentName { get; set; }

    }
    [MetadataType(typeof(tblDepartmentCustom))]
    public partial class tblDepartmentMaster
    {
    }

实体框架生成的原始类如下所示。

public partial class tblDepartmentMaster
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public tblDepartmentMaster()
        {
            this.tblDesignationMasters = new HashSet<tblDesignationMaster>();
        }


        public int DepartmentId { get; set; }
        public string DepartmentName { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<tblDesignationMaster> tblDesignationMasters { get; set; }
    }

所以问题在于,无论何时我尝试验证模型状态,它都是真的。下面是代码。

@model EmployeeManager.Models.tblDepartmentCustom
@{
    ViewBag.Title = "InsertDepartment";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}<div class="col-md-4">
    @using (Html.BeginForm("InsertDepartment", "Departments", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()
        <span class="error-class">@ViewBag.FoundError</span>
        <br />
        <label>Department Name</label>
        @Html.TextBoxFor(m => m.DepartmentName, new { @class = "form-control" })
        <br />
        <input type="submit" class="btn btn-info" value="Add Department" />
    }
</div>

以下的行动。

[HttpGet]
        public ActionResult InsertDepartment()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("InsertDepartment")]
        public ActionResult InsertDepartmentPost()
        {

            using (PMSEntities dc = new PMSEntities())
            {

                tblDepartmentMaster dm = new tblDepartmentMaster();
                TryUpdateModel(dm);
                if(ModelState.IsValid)
                {
                    dc.tblDepartmentMasters.Add(dm);
                    dc.SaveChanges();
                    return View("_Success");
                }
                else
                {
                    ViewBag.FoundError = "Department name is required.";
                    return View();
                }
                           }
        }

1 个答案:

答案 0 :(得分:0)

为了使部分类起作用,两个部分必须具有相同的命名空间。您不必在文件结构周围移动实际文件,只需编辑tblDepartmentCustom的命名空间以匹配tblDepartmentMaster的命名空间。