I'm using the Ado.net 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 3.5.0.0.
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
}
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
}
Something like this should work:
if (publishContext.Author.Select(a => a.AuthodSSID).Where(id => id == 20).Take(1) == null)
// It doesn't exist
else
// 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.