C#SQL LINQ查询和验证方法不起作用

问题描述:

我知道这对某些人来说听起来确实很简单,对此我深表歉意,但是我是C#和LINQ的新手.

我正在尝试编写一种方法来搜索数据库中是否存在以INT表示的ID.我已经编写了一种处理错误的方法,并且编写的代码的目的是在存在唯一ID的情况下停止insert语句,而不是尝试将其插入并失败.错误处理有效,但不适用于这一令人沮丧的功能.

我已经在Internet上进行了一些研究,并尝试了几种方法来解决我的问题,但到目前为止没有任何效果.我写了两种我认为可以的方法,但是它仍然没有按照我想要的去做.我尝试过的方法如下.如果有人可以让我走上正确的道路,我将不胜感激!

I know this must sound really simple to some and I apologise for that but I am new to C# and LINQ.

I am trying to write a method which searches whether an ID which is represented as an INT in my database exists. I have written a method to handle errors and the purpose of the code I have written is to stop the insert statement if the unique ID is present, instead of trying to insert it and failing. The error handing works but is not working for this one function which is very frustrating.

I have done some research on the Internet and have tried several methods to solve my problem by so far nothing has worked. I wrote two methods which I believe to be alright but it is still not doing what I want it to do. The methods I have tried are below. If anyone can put me on the right track I would be very grateful!

int EmployeeIDCatched = int.Parse(EmployeeIDTextBox.Text);

var Database = new DataSet();

// The first method I tried

bool Query1 = Database.Employee.Any(Employee => Employee.EmployeeID == EmployeeIDCatched);

if (Query1 == true)
{
ErrorList.Add("The unique ID is taken");
Valid = false;
}

// The second method I tried

var Query2 = from Employee in Database.Employee
             where (Employee.EmployeeID == EmployeeIDCatched)
             select Employee.EmployeeID;

if (Query2.Count() > 0)
{
ErrorList.Add("The unique ID is taken");
Valid = false;
}



我已将我的数据集数据库称为.我有一个名为Employee的表,正在搜索表中名为EmployeeID的字段.我从文本框中提取的值和在数据库中搜索的值都是整数.



I have called my Dataset Database. I have a table called Employee and am searching a field inside the table which is called EmployeeID. Both the value I am pulling from the text box and searching for in the database are integers.

尝试以下操作:

Try this:

int Query2 = (from Employee in Database.Employee
             where Employee.EmployeeID == EmployeeIDCatched
             select (Employee.EmployeeID)).Count();

if (Query2 > 0)
{
ErrorList.Add("The unique ID is taken");
Valid = false;
}



希望能正常工作.



Hopefully will work.


尝试一下:



Try this:



int Query2 = (from Employee in Database.Employee
             where Employee.EmployeeID == EmployeeIDCatched
             select new{Employee.EmployeeID}).Count();

if (Query2 > 0)
{
ErrorList.Add("The unique ID is taken");
Valid = false;
}