The easiest way to verify a record exists or not in Linq to Entity Query

in the stored procedure we can verify that the record exists or is not using the following query for fast performance

if EXISTS ( Select 1 from Table_Name where id=@id )

But what about the Linq request. right now i have to store the whole data in an object like this

UserDetail _U=db.UserDetails.where(x=>x.id==1).FirstOrDefault();

Any solution?

+4
source share
5 answers

Use Linq Anyiebool exist = db.UserDetails.Any(x => x.id == 1);

if(db.UserDetails.Any(x => x.id == 1)) {
    var userDetail = db.UserDetails.FirstOrDefault(x => x.id == 1);
}
+4
source

Just check

if(_U == null)

This way you get what you want in a single request, and you do not need to execute the add request, for example

db.UserDetails.Any(x => x.id == 1)
+1
source
bool exist = db.UserDetails.Where(x=>x.id==1).Any();
if(exist){
  //your-code
 }else{
  //your-code
}
+1

, . .

UserDetails objUserDetails =db.UserDetails.FirstOrDefault(x => x.id == 1);
if(objUserDetails==null)
{
    // Do something
}
else
{
    // do something with objUserDetails
}
+1
var qry = db.User_Detail.Where(x => x.User_Id == 1).FirstOrDefault();

if(qry !=null)
{
// Do something
}
else
{
return false;
}

...

+1

Source: https://habr.com/ru/post/1676624/


All Articles