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)