IM91
IM91

Reputation: 37

Unique ID Validation Query

I am writing a statement which checks my database to see if a value exists so that it does not insert a record to the database if it has the same unique ID. I have my exceptions working for the rest of my fields however I am having trouble retrieving data from the database to compare to the value I have caught from the database. Below is an example of my code.

int EmployeeIDCatched = int.Parse(employeeIDTextBox.Text);
var EmployeeIDQuery = from EmployeeID in EmployeeDataSet.Employee select EmployeeIDCatched;
if (EmployeeIDQuery.Equals(EmployeeIDCatched))

I was rather hoping someone might be able to correct this for me.

The dataset is called EmployeeDataSet, the table is called Employee and the row I am searching is called EmployeeID

If anyone could help I would be very grateful!

Upvotes: 1

Views: 619

Answers (2)

Seb Nilsson
Seb Nilsson

Reputation: 26428

I'm assuming you want only one hit and you want the employee-object returned:

int employeeIDCatched = int.Parse(employeeIDTextBox.Text);

var matchingEmployee = (from employee in EmployeeDataSet.Employee
                        where employee.ID.Equals(employeeIDCatched)
                        select employee).FirstOrDefault();

Update: Not sure if I didn't read the question close enough or if the detail changed, but here is now to just get a bool-result:

int employeeIDCatched = int.Parse(employeeIDTextBox.Text);

bool hasMatchingEmployee = EmployeeDataSet.Employee.Any(employee =>
    employee.ID.Equals(employeeIDCatched));

Upvotes: 1

Anthony Faull
Anthony Faull

Reputation: 17977

You can use the Any method to check if a row exists.

var selectedEmployeeId = int.Parse(employeeIDTextBox.Text);
if (EmployeeDataSet.Employee.Any(e => e.EmployeeID == selectedEmployeeId))

Upvotes: 0

Related Questions