LightSwitch 2011数据字段唯一性验证方案

  LightSwitch 2011 数据字段唯一性验证方案

验证单表数据的某个字段不能输入重复值

  设置实体字段唯一索引

  如果不写代码,那么验证只会在用户提交[保存]数据后,会提示错误,很明显这样的用户体验并不好,因此还需要做以下步骤

  添加自定义验证

 
 
 
 
  1.   partial void UserName_Validate(EntityValidationResultsBuilder results)  
  2.   {  
  3.   // results.AddPropertyError("<错误消息>");  
  4.   bool duplicateExists = false 
  5.   switch (this.Details.EntityState)  
  6.   {  
  7.   case EntityState.Added:  
  8.   {  
  9.  //基于页面未提交数据的验证  
  10.   duplicateExists = (from item in DataWorkspace.ApplicationData.Details.GetChanges().AddedEntities.OfType<Employee>()  
  11.  where item.UserName == this.UserName && !string.IsNullOrEmpty(this.UserName)  
  12.   select item).Count() > 1 ? true : false 
  13.   //基于数据库的验证  
  14.   if (!duplicateExists)  
  15.   duplicateExists = (from Employee emp in DataWorkspace.ApplicationData.Employees.Cast<Employee>()  
  16.   where this.UserName != null &&  
  17.   string.Compare(emp.UserName, this.UserName.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0  
  18.   select emp).Any();  
  19.   break 
  20.   }  
  21.   case EntityState.Modified:  
  22.   {  
  23.   duplicateExists = (from item in DataWorkspace.ApplicationData.Details.GetChanges().ModifiedEntities.OfType<Employee>()  
  24.   where item.UserName == this.UserName && !string.IsNullOrEmpty(this.UserName)  
  25.   select item).Count() > 1 ? true : false 
  26.   if (!duplicateExists)  
  27.   duplicateExists = (from Employee emp in DataWorkspace.ApplicationData.Employees.Cast<Employee>()  
  28.   where this.UserName != null &&  
  29.   string.Compare(emp.UserName, this.UserName.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0  
  30.   select emp).Any();  
  31.   break 
  32.   }  
  33.  }  
  34.   if (duplicateExists)  
  35.   {  
  36.   results.AddPropertyError(string.Format("该用户[{0}]已经存在。", UserName));  
  37.   } 

  运行结果如下

原文链接:http://www.cnblogs.com/neozhu/archive/2011/10/19/2217221.html

【编辑推荐】

  1. 小试一下微软开发框架LightSwitch
  2. Visual Studio简化版推出 供非专业人员使用
  3. Visual Studio LightSwitch安装与配置详解
  4. 详解Visual Studio 2010辅助敏捷测试
  5. Visual Studio 2010中特殊表格的开发
THE END