Implement UniqueAttribute uniqueness constraints and sqlunique Constraints

Source: Internet
Author: User

Implement UniqueAttribute uniqueness constraints and sqlunique Constraints

Using System; using System. componentModel. dataAnnotations; using System. data. entity; namespace Zwj. TEMS. base {// <summary> /// Unique Identifier /// </summary> [AttributeUsage (AttributeTargets. property, AllowMultiple = false, Inherited = true)] public class UniqueAttribute: ValidationAttribute {protected string tableName; protected string filedName; public UniqueAttribute (string tableName, string filedName ){ This. tableName = tableName; this. filedName = filedName;} public override Boolean IsValid (Object value) {bool validResult = false; // TEMSContext is the DB context class in my project. To use it in other projects, change it to the actual DB context class! Using (TEMSContext context = new TEMSContext () {string sqlCmd = string. format ("select count (1) from [{0}] where [{1}] = @ p0", tableName, filedName); context. database. connection. open (); var cmd = context. database. connection. createCommand (); cmd. commandText = sqlCmd; var p0 = cmd. createParameter (); required parametername = "@ p0"; required value = value; cmd. parameters. add (p0); int result = Convert. toInt32 (cmd. executeScalar (); validResult = (result <= 0);} return validResult ;}}}

The following describes how to use an object:

/// <Summary> /// category code /// </summary> [Required ()] [MaxLength (50)][Unique ("Category", "CategoryCode")][Display (Name = "Category Code")] public string CategoryCode {get; set ;}

 

The call and verification methods are as follows:

// I have written a unit test verification method here. You can use it in your project. public void ValidateEntity (object entity) {var t = entity. getType (); var properties = t. getProperties (); foreach (var p in properties) {UniqueAttribute [] attrs; if (p. tryGetAttribute <UniqueAttribute> (out attrs) {bool result = attrs [0]. isValid (p. getValue (entity, null); Assert. isTrue (result, "the verification is not unique and there are duplicate values! ");}}}
 
Public static class ClassExtension {// <summary> /// try to obtain the specified category feature /// </summary> /// <typeparam name = "TAttribute"> </typeparam> /// <param name = "p"> </param> /// <param name = "returnAttrs"> </param> /// <returns> </returns> public static boolTryGetAttribute<TAttribute> (this PropertyInfo p, out TAttribute [] returnAttrs) where TAttribute: Attribute {var attrs = p. GetCustomAttributes (typeof (TAttribute), false); if (attrs! = Null & attrs. length> 0) {returnAttrs = attrs. select (t => t as TAttribute ). toArray (); return true;} returnAttrs = null; return false ;}}
 

 



The following is a blog article about how to generate a unique index in the database, but does not explain how to perform uniqueness verification in C, this article is just a supplement.
How to use the Unique constraint (Unique) in EF CodeFirst)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.