[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Private
  • Views: 47
  • Last Modified:

Check if record already exist using LINQ to sql

HI:
I'm using LINQ to sql with c#
I have a text box on a web page , after entering a value to that box
I need to validate whither if this value exist in myTable or not
Var xmyTable = (from ymyTable in objDataContext.myTables
                              Select new 
                             {
                               ymyTable.myCode
                              ymyTable.myNmae
                             }

Open in new window

please help
0
Mohammad Alsolaiman
Asked:
Mohammad Alsolaiman
  • 2
  • 2
3 Solutions
 
Fernando SotoCommented:
Hi M_SOLAIMAN;

If you wish to just test if the value exist in the database then you can use a query like the following. Please replace the ColumnName place holder with the actual column name the data is in. The variable xexist will contain the boolean true if it does and false if it does NOT.

var xexist = (from ymyTable in objDataContext.myTables
              where ymyTable.ColumnName == TextBox.Text
              select true)FirstOrDefault();

Open in new window

0
 
Chris WatsonCommented:
Here's a variation of Fernando's solution.

var exists = objDataContext.myTables.Any(myTable => myTable.ColumnName == TextBox.Text);

Open in new window

0
 
Mohammad Alsolaimanapplication programmerAuthor Commented:
i couldn't understand this line of code!
select true)FirstOrDefault();

Open in new window

would you please explane
0
 
Fernando SotoCommented:
The question states that you want to verify whither the value exist in the table. That is a true/false type query. A query returns a collection of object to the caller and to turn that into a true or false predicate. To do that, turn a collection into a true or false value we say that if the record we are testing makes it to the select statement just return a true value for that record. That would return a collection of boolean type true. To turn the collection of true values into a single value of true we take the first element of the collection and return it. Now if the collection that is returned is empty then we need to return false. That is what the FirstOrDefault method in the query does. It will take the first element and return it, if the collection is empty it returns the default value for a boolean which is false.
0
 
Mohammad Alsolaimanapplication programmerAuthor Commented:
thanks a lot, and very sorry for late
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now