zoukankan      html  css  js  c++  java
  • MVC+EF 自定义唯一性验证

       最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。

       十年河东十年河西,莫欺少年穷

       学无止境,精益求精

       本篇提供二种方法,希望大家喜欢

       1、自定义验证属性,利用数据验证和注解来完成唯一性验证。

       假设我们有如下表:

        public class Student
        {
            [Key]
            public int Id { get; set; }
            [Required]
            [StringLength(10)]
            public string Name { get; set; }//姓名
            [StringLength(2)]
            public string Sex { get; set; }//性别
    
            [StringLength(18)]
            public string StudentNum { get; set; }//学号
    
            [StringLength(100)]
            public string StudentAddress { get; set; }//地址
        }

       现在我们使 学号 字段唯一,不允许重复

       我们创建如下验证过滤器

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    using System.Web.Http.Filters;
    using EF_Test.DAL;
    
    namespace EF_Test.Attribute
    {
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
        public class UniqueAttribute :   ValidationAttribute
        {
            public override Boolean IsValid(Object value)
            {
                //校验数据库是否存在当前Key
                if (value != null)
                {
                    return check(value);
                }
                return false;
            }
    
            private bool check(object o)
            {
                using (StudentContext db = new StudentContext())
                {
                    return db.Students.Where(item => item.StudentNum == o.ToString()).Count() <= 0;
                }
            }
        }
    }

       根据上述方法check()来判断学号是否唯一

       最后我们对学号字段作如下修改:

            [Unique(ErrorMessage="学号不允许重复")]
            [StringLength(18)]
            public string StudentNum { get; set; }//学号

       方法2、

       在XXXInitializer类中的Seed()方法中添加数据库唯一性验证语句

             protected override void Seed(StudentContext context)
            {
                context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_Category_Title ON Student (StudentNum)");//添加数据库唯一系验证 Student数据表   StudentNum 字段
            }

       在DBcontext中添加引用:

        public class StudentContext : DbContext
        {
            public StudentContext()
                : base("StudentContext")//指定连接字符串
            {
                Database.SetInitializer<StudentContext>(new StudentInitializer());
            }
            public DbSet<Student> Students { get; set; }
            public DbSet<Course> Courses { get; set; }
            public DbSet<Score> Scores { get; set; }
    
            /// <summary>
            /// OnModelCreating方法中的modelBuilder.Conventions.Remove语句禁止表名称正在多元化。如果你不这样做,所生成的表将命名为Students、Courses和Enrollments。相反,表名称将是Student、Course和Enrollment。开发商不同意关于表名称应该多数。本教程使用的是单数形式,但重要的一点是,您可以选择哪个你更喜欢通过包括或省略这行代码的形式。
            /// </summary>
            /// <param name="modelBuilder"></param>
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            }
        }

       方法二验证如下:   

       

       方法一大家自行验证

       其实大家现在应该明白了,所有的数据验证我们都是可以自定义的!、

       我们可以根据我们的业务需求自定义一套属于我们的数据验证容器!

       @陈卧龙的博客

  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/chenwolong/p/unqiue.html
Copyright © 2011-2022 走看看