LightSwitch 2011數(shù)據(jù)字段唯一性驗(yàn)證方案
作者:阿新 
  我們將談到的是LightSwitch 2011數(shù)據(jù)字段唯一性驗(yàn)證方案,這個方案其實(shí)不復(fù)雜。希望對大家有所幫助。
 LightSwitch 2011 數(shù)據(jù)字段唯一性驗(yàn)證方案

驗(yàn)證單表數(shù)據(jù)的某個字段不能輸入重復(fù)值
設(shè)置實(shí)體字段唯一索引

如果不寫代碼,那么驗(yàn)證只會在用戶提交[保存]數(shù)據(jù)后,會提示錯誤,很明顯這樣的用戶體驗(yàn)并不好,因此還需要做以下步驟
添加自定義驗(yàn)證

- partial void UserName_Validate(EntityValidationResultsBuilder results)
 - {
 - // results.AddPropertyError("<錯誤消息>");
 - bool duplicateExists = false
 - switch (this.Details.EntityState)
 - {
 - case EntityState.Added:
 - {
 - //基于頁面未提交數(shù)據(jù)的驗(yàn)證
 - duplicateExists = (from item in DataWorkspace.ApplicationData.Details.GetChanges().AddedEntities.OfType<Employee>()
 - where item.UserName == this.UserName && !string.IsNullOrEmpty(this.UserName)
 - select item).Count() > 1 ? true : false
 - //基于數(shù)據(jù)庫的驗(yàn)證
 - if (!duplicateExists)
 - duplicateExists = (from Employee emp in DataWorkspace.ApplicationData.Employees.Cast<Employee>()
 - where this.UserName != null &&
 - string.Compare(emp.UserName, this.UserName.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0
 - select emp).Any();
 - break
 - }
 - case EntityState.Modified:
 - {
 - duplicateExists = (from item in DataWorkspace.ApplicationData.Details.GetChanges().ModifiedEntities.OfType<Employee>()
 - where item.UserName == this.UserName && !string.IsNullOrEmpty(this.UserName)
 - select item).Count() > 1 ? true : false
 - if (!duplicateExists)
 - duplicateExists = (from Employee emp in DataWorkspace.ApplicationData.Employees.Cast<Employee>()
 - where this.UserName != null &&
 - string.Compare(emp.UserName, this.UserName.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0
 - select emp).Any();
 - break
 - }
 - }
 - if (duplicateExists)
 - {
 - results.AddPropertyError(string.Format("該用戶[{0}]已經(jīng)存在。", UserName));
 - }
 
運(yùn)行結(jié)果如下

原文鏈接:http://www.cnblogs.com/neozhu/archive/2011/10/19/2217221.html
【編輯推薦】
責(zé)任編輯:彭凡 
                    來源:
                    博客園
 














 
 
 











 
 
 
 