private bool Validate(Contact contact, out string errorMsg) { errorMsg = null; if (string.IsNullOrWhiteSpace(contact.Name)) { errorMsg = "姓名不可为空"; return(false); } if (string.IsNullOrWhiteSpace(contact.Phone)) { errorMsg = "电话号码不可为空"; return(false); } if (!phoneRegex.IsMatch(contact.Phone)) { errorMsg = "电话号码格式错误"; return(false); } if (!string.IsNullOrWhiteSpace(contact.Email) && !emailRegex.IsMatch(contact.Email)) { errorMsg = "电子邮件格式错误"; return(false); } return(true); }
public void Remove() { Contact temp = Selected; this.Contacts.Remove(temp); using (ContactsDbContext context = new ContactsDbContext()) { DbEntityEntry <Contact> entry = context.Entry(temp); entry.State = EntityState.Deleted; context.SaveChanges(); } }
public bool Save(out string errorMsg) { if (!Validate(Selected, out errorMsg)) { return(false); } errorMsg = null; using (ContactsDbContext context = new ContactsDbContext()) { string cstr = ((IObjectContextAdapter)context).ObjectContext.Connection.ConnectionString; if (Selected.Id == 0) { context.ContactSet.Add(Selected); } else { Contact existed = (from c in context.ContactSet where c.Id == Selected.Id select c).FirstOrDefault(); if (existed != null) { existed.Name = Selected.Name; existed.Email = Selected.Email; existed.Phone = Selected.Phone; existed.Photo = Selected.Photo; context.Entry(existed).State = EntityState.Deleted; } else { return(true); // 设置断点来debug } } bool hasChange = context.ChangeTracker.HasChanges(); if (hasChange) { try { int resultAffected = context.SaveChanges(); } catch (Exception ex) { string error = ex.Message; throw; } } // 确认 //List<Contact> news = context.ContactSet.SqlQuery("select * from contact").ToList(); //int count = news.Count; //bool hasAdded = count == Contacts.Count; } return(true); }