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 EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.
First, we check if the record exists with the EXISTS keyword. EXISTS executes the query we tell it to (the SELECT ) and returns a boolean value. If it finds the record, we return 'This record already exists!'
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With