首页 > 代码库 > 如何避免在EF自动生成的model中的DataAnnotation被覆盖掉

如何避免在EF自动生成的model中的DataAnnotation被覆盖掉

相信很多人刚接触EF+MVC的时候,会有这个疑问,就是当我们在model类中加验证信息的时候,会在重新生成model的时候被重写掉。这里介绍一个方法:

比如我有个Employee类是从数据库中生成到model中的,我们可以在Models文件夹中创建一个部分类名称与Employee类同名,然后在新建的部分类中加上我们需要验证信息,这时我们在view页面中引用Models.Employee做为页面model类。这样当我们重新生成model的时候,我们自己定义的部分类Employee就不会受影响了。

下面是样例代码:

从数据库中生成的Employee:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ValidationDemo
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employee
    {
        public Employee()
        {
            this.Employees1 = new HashSet<Employee>();
            this.Orders = new HashSet<Order>();
            this.Territories = new HashSet<Territory>();
        }
    
        public int EmployeeID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public Nullable<System.DateTime> BirthDate { get; set; }
        public Nullable<System.DateTime> HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string HomePhone { get; set; }
        public string Extension { get; set; }
        public byte[] Photo { get; set; }
        public string Notes { get; set; }
        public Nullable<int> ReportsTo { get; set; }
        public string PhotoPath { get; set; }
        public Nullable<int> COL1 { get; set; }
    
        public virtual ICollection<Employee> Employees1 { get; set; }
        public virtual Employee Employee1 { get; set; }
        public virtual ICollection<Order> Orders { get; set; }
        public virtual ICollection<Territory> Territories { get; set; }
    }
}
创建一个部分类,命名为Employee:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ValidationDemo.Models
{
    public partial class Employee
    {
        public int EmployeeID { get; set; }
        [Required]//There is my dataAnnotation
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public Nullable<System.DateTime> BirthDate { get; set; }
        public Nullable<System.DateTime> HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string HomePhone { get; set; }
        public string Extension { get; set; }
        public byte[] Photo { get; set; }
        public string Notes { get; set; }
        public Nullable<int> ReportsTo { get; set; }
        public string PhotoPath { get; set; }
        public Nullable<int> COL1 { get; set; }
    }
}

现在,我们就可以在页面中引用如下:
@model ValidationDemo.Models.Employee

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Employee</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName)
                @Html.ValidationMessageFor(model => model.LastName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName)
                @Html.ValidationMessageFor(model => model.FirstName)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TitleOfCourtesy, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.TitleOfCourtesy)
                @Html.ValidationMessageFor(model => model.TitleOfCourtesy)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BirthDate, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BirthDate)
                @Html.ValidationMessageFor(model => model.BirthDate)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.HireDate, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.HireDate)
                @Html.ValidationMessageFor(model => model.HireDate)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address)
                @Html.ValidationMessageFor(model => model.Address)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City)
                @Html.ValidationMessageFor(model => model.City)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Region, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Region)
                @Html.ValidationMessageFor(model => model.Region)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PostalCode, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PostalCode)
                @Html.ValidationMessageFor(model => model.PostalCode)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Country, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Country)
                @Html.ValidationMessageFor(model => model.Country)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.HomePhone, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.HomePhone)
                @Html.ValidationMessageFor(model => model.HomePhone)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Extension, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Extension)
                @Html.ValidationMessageFor(model => model.Extension)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Photo, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Photo)
                @Html.ValidationMessageFor(model => model.Photo)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Notes, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Notes)
                @Html.ValidationMessageFor(model => model.Notes)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ReportsTo, "ReportsTo", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ReportsTo", String.Empty)
                @Html.ValidationMessageFor(model => model.ReportsTo)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhotoPath, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhotoPath)
                @Html.ValidationMessageFor(model => model.PhotoPath)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.COL1, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.COL1)
                @Html.ValidationMessageFor(model => model.COL1)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value=http://www.mamicode.com/"Create" class="btn btn-default" />>最后,我们需要将名为Create的Action将Models下的Employee类的实例作为参数传入:
[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="EmployeeID,LastName,FirstName,Title,TitleOfCourtesy,BirthDate,HireDate,Address,City,Region,PostalCode,Country,HomePhone,Extension,Photo,Notes,ReportsTo,PhotoPath,COL1")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ReportsTo = new SelectList(db.Employees, "EmployeeID", "LastName", employee.ReportsTo);
            return View(employee);
        }

OK,大功告成。