How do you check if Record exists

asp.net c# entity-framework linq

Question

I have a form that inserts data. I want to see if the record already exists in the database to prevent duplicates. I'm not exactly sure when this needs to happen. 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've witnessed it done using if statements that employ.Any() But I am unable to make it operate properly. I also don't know what it needs to return for me to write an error message.Contact Name already exists .

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

Accepted Answer

You could employ any of the following methods:

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 that called AddContact would examine the return value and determine whether to show the user a message asking for confirmation or an error.

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

Popular Answer

Check as follows:

bool doesExistAlready = _db.Contacts.Any(o => o.ContactName == ContactName);

Try this if it doesn't work:

bool doesExistAlready = _db.Contacts.Count(o => o.ContactName == ContactName) > 0;

To see the actual SQL being produced, enable SQL tracing and debugging.



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