Before adding a new record, make sure it already exists.

c# entity-framework


I'm using the Entity Framework for the first time and I need to check if this record exist before I insert it to the database. Preferably I'd search if AuthodSSID exists and not the key (AuthorID). I'm using VS2010, Framework 4. System.Data.Entity is

I googled, but found no answer for this question.

PublishingCompanyEntities publishContext;
publishContext = new PublishingCompanyEntities();

private void createNew_Click(object sender, EventArgs e)
    Author newAuthor = new Author();
    newAuthor.FirstName = firstName.Text;
    newAuthor.LastName = lastName.Text;
    newAuthor.AuthodSSID = 20;
    newAuthor.AuthorID = 10
//Check if record exist here
    publishContext.AddToAuthor(newAuthor);//insert if does not exist

2/15/2012 3:26:38 AM

Accepted Answer

The only way to check if a record exists is to query the record and see if anything comes back:

var existingAuthorCount = publishContext.Author.Count(a => a.AuthodSSID == 20);
if (existingAuthorCount == 0) 
    // Do your insert
2/15/2012 3:31:22 AM

Popular Answer

Something like this should work:

if (publishContext.Author.Select(a => a.AuthodSSID).Where(id => id == 20).Take(1) == null)
    // It doesn't exist
    // It does exist

Based on my (albeit fundamental) understanding this should produce a SQL statement equivalent to:

SELECT TOP(1) AutodSSID FROM Author WHERE AuthodSSID = 20;

Another simpler approach may be to use the Any extension method:

if (!publishContext.Author.Any(a => a.AuthodSSID == 20))
    // Put your insert logic here.

Related Questions


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