2

I am currently trying to check if there exists an instance of an object with a unique ID in a SQL Table. So as to not place duplicates. Here is a sample of what I currently have:

string ui = someObj.getUniqueID();

IQueryable<String> checkDataQuery = from cdq in db.SomeObjects
                                           where cdq.UniqueID == ui
                                           select cdq.UniqueID;

if (checkDataQuery != ui) // This is just my attempt at making sure that
                          // the query actually returned something and not 
                          // the string representing nothing found, so if there
                          // is a better checking method that would even more helpful.

The main issue I am running into is that I can not access checkDataQuery as a string. I attempted casting it, and using the .Single()/.First() methods, however, the former had no success, and the latter made the single string being returned into a list of characters.

1 Answer 1

2

You can check the result with Enumerable.Any like:

bool ifExists = db.SomeObjects.Any(r=> r.UniqueID == ui);

If you want to get the object, then you can use FirstOrDefault and check for null like:

var dbObject = db.SomeObjects.FirstOrDefault(r=> r.UniqueID == ui);
if(dbObject != null)
{
  //record exists
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am still fairly new to C# and Linq, if you could, can you explain the "=>" operator, the rest reads fairly straightforward.
@FenrirProtocol, LINQ uses two styles , method syntax and query syntax. What I have used is method syntax. => used in the code is basically a Lambda Expression

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.