How do you check if Record exists

asp.net c# entity-framework linq

Question

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.

1
10
5/7/2015 8:48:27 PM

Accepted Answer

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.

24
12/12/2012 12:58:44 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow