Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to check record is exist or not in Linq to Entity Query

in store procedure we can check record is exist or not using following query for fast performance

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

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

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

Any Solution?

like image 619
Manish Vadher Avatar asked May 08 '17 04:05

Manish Vadher


3 Answers

Use Linq's Any ie bool 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);
}
like image 124
Nkosi Avatar answered Sep 21 '22 22:09

Nkosi


bool exist = db.UserDetails.Where(x=>x.id==1).Any();
if(exist){
  //your-code
 }else{
  //your-code
}
like image 36
Amirhosein Rajabi Avatar answered Sep 17 '22 22:09

Amirhosein Rajabi


Just check

if(_U == null)

This way you will get what you want in single query and you not need to execute addition query like

db.UserDetails.Any(x => x.id == 1)
like image 29
Imad Avatar answered Sep 18 '22 22:09

Imad