Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if Record exists

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.

like image 641
jackncoke Avatar asked Dec 12 '12 00:12

jackncoke


2 Answers

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.

like image 74
siger Avatar answered Oct 01 '22 16:10

siger


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.

like image 30
Arash Emami Avatar answered Oct 01 '22 15:10

Arash Emami