public static bool GetPersonByNameAmbiguous(string name, out Person person, out string errorMessage, WMSEntities wmsEntities = null) { if (wmsEntities == null) { wmsEntities = new WMSEntities(); } //如果输入的名字是空的,直接抛出异常。这儿不允许传入空的 if (string.IsNullOrWhiteSpace(name)) { throw new Exception("GetPersonByNameAmbiguous()函数不允许传入空的零件名字(代号)!空格也不行!请使用string.IsNullOrWhiteSpace()自行判空"); } //首先精确查询,如果没有,再模糊查询 person = (from p in wmsEntities.Person where p.Name == name select p).FirstOrDefault(); //如果搜到了,直接返回 if (person != null) { errorMessage = null; return(true); } //如果没搜到,模糊搜索 Person[] persons = (from p in wmsEntities.Person where p.Name.Contains(name) select p).ToArray(); //如果模糊搜索也没搜到,提示错误 if (persons.Length == 0) { person = null; errorMessage = "未找到人员:" + name; return(false); } //正好一个就太好了,直接返回这一个 if (persons.Length == 1) { person = persons[0]; errorMessage = null; return(true); } else //如果搜到了多个,那就得让用户选是哪一个了 { Person selectedPerson = FormChooseAmbiguousPerson.ChoosePerson( persons, name); if (selectedPerson == null) { errorMessage = "用户取消了导入"; return(false); } else { person = selectedPerson; errorMessage = null; return(true); } } }
public static Person ChoosePerson(Person[] persons, string srcNameAmbiguous) { //传入空数组直接返回空 if ((persons == null || persons.Length == 0)) { return(null); } //否则新建一个选择窗口,开始选择 FormChooseAmbiguousPerson form = new FormChooseAmbiguousPerson(); form.listBox.Items.AddRange((from p in persons select new ItemAndString() { Item = p, String = p.Name }).ToArray()); form.label1.Text = string.Format("您输入的人员\"{0}\"不明确,请选择下列零件中的一个", srcNameAmbiguous); form.ShowDialog(); return(form.selectedItem); }