LightSwitch 2011 数据字段唯一性验证方案
生活随笔
收集整理的這篇文章主要介紹了
LightSwitch 2011 数据字段唯一性验证方案
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
LightSwitch 2011 數據字段唯一性驗證方案
?
?
驗證單表數據的某個字段不能輸入重復值
?
設置實體字段唯一索引
如果不寫代碼,那么驗證只會在用戶提交[保存]數據后,會提示錯誤,很明顯這樣的用戶體驗并不好,因此還需要做以下步驟
添加自定義驗證
?View Code
?partial?void?UserName_Validate(EntityValidationResultsBuilder?results)
????????{
????????????//?results.AddPropertyError("<錯誤消息>");
????????????bool?duplicateExists?=?false;
???????????
????????????switch?(this.Details.EntityState)
????????????{
????????????????case?EntityState.Added:
????????????????????{
????????????????????????//基于頁面未提交數據的驗證
????????????????????????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;
????????????????????????//基于數據庫的驗證
????????????????????????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}]已經存在。",?UserName));
????????????}
運行結果如下
轉載于:https://www.cnblogs.com/neozhu/archive/2011/10/19/2217221.html
總結
以上是生活随笔為你收集整理的LightSwitch 2011 数据字段唯一性验证方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#数“.NET研究”据本地存储方案之S
- 下一篇: ListView的Adapter使用(绑