I have a form that does an insert. I want to see if the record already exists in the database to prevent duplicates. I am a little unsure of when this has to go down. In the codebehind for the controls that is the form or in the Class that I call on to perform the insert. Below is the class that is where I am thinking it goes.
public class AddContacts
{
public int AddContact(string ContactName)
{
var myContact = new Solutions.Models.Contact();
myContact.ContactName = ContactName;
ItemContext _db = new ItemContext();
_db.Contacts.Add(myContact);
_db.SaveChanges();
return myContact.ContactID;
}
}
I have seen it done with If statements that use .Any() but i cannot get it work right. Nor do I understand what it would need to return in order for me to post a error message Contact Name already exists.
You could use the Any method like this:
The method calling AddContact would check the return value and decide whether to display an error or confirmation message to the user.