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:
bool contactExists = _db.Contacts.Any(contact => contact.ContactName.Equals(ContactName));
if (contactExists)
{
return -1;
}
else
{
_db.Contacts.Add(myContact);
_db.SaveChanges();
return myContact.ContactID;
}
The method calling AddContact would check the return value and decide whether to display an error or confirmation message to the user.
Do a check like this:
bool doesExistAlready = _db.Contacts.Any(o => o.ContactName == ContactName);
If that doesn't work, try this:
bool doesExistAlready = _db.Contacts.Count(o => o.ContactName == ContactName) > 0;
Turn on SQL tracing/debugging so you see the actual sql being produced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With