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

c# entity-framework

Question

I'm using the Ado.net Entity Framework for the first time, thus before I enter this entry into the database, I need to make sure it already exists. I would rather check for the presence of AuthodSSID than the key (AuthorID). I'm using Framework 4 and VS2010. System. Data.Entity is version 3.5.0.

I searched Google for a solution, but I came up empty.

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

}
1
12
2/15/2012 3:26:38 AM

Accepted Answer

The only method to determine if a record is present is to query it and see what results there are:

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

Popular Answer

This kind of stuff ought to work:

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

According to my (although basic) understanding, this ought to result in a SQL query like to:

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

Another simpler approach may be to use theAny extension strategy:

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


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