简体   繁体   中英

Check if username already exists in database using linq

What would be the linq query to check if the username already exists in database? Say my table name is "DeskOperators" and I have the column name "Username"

You can use Enumerable.Any . It will return true of any of record has user name you are looking for.

DeskOperators.Any(r=>r.Username == userName)

You can use Enumerable.Single or Enumerable.SingleOrDefault to ensure that only one record match the condition.

   var result = (from row in DeskOperators 
                          where row.Username== txtUsername.Text.ToString()
                          select row).ToList();

if (result.Count() != 0)
            {
                lblmsg1.Visible = true;
                lblmsg.Text = "User Name is Already Exist";

            }
            else
            {
               //your code.

            }

try with this one.

This will select the first username that matches but won't throw an exception if none is found (you just end up with a blank set).

var i = (from c in DeskOperators 
   where c.Username == CodeHugger 
   select c.CustomerID).FirstOrDefault(); 

像这样

 if (!dbcontex.table.Any(s => s.column == value))

I have have written the following code to register user. I am checking if the username already exists. I tried the following and it worked for me:

var checkexistance = (from reg in db.RegisterOperatorTables  where reg.OperatorName == operatorModel.OperatorName select reg);
            if (checkexistance.Count()>0)
            {
                return false;
            }
            else
            {
                table.OperatorName = operatorModel.OperatorName;
                table.OperatorPassword = operatorModel.Password;
                db.RegisterOperatorTables.InsertOnSubmit(table);
                db.SubmitChanges();

                return true;
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM