How to check the user exists in DB using Linq Concepts?


To check the user exists in DB using LINQ Concepts

1. Create .dbml file using LINQ to SQL Classes template
2. Right Click project -> Add New Item -> Select LINQ to SQL Classes
3. Set up your Database connection
4. Drag the table

Create Common Class file (ex.. First.cs) and write the below function



DataClassesDataContext objdc = null;
public bool CheckUserExists(string strUserID)
{
objdc = new DataClassesDataContext();
UserMst objUserMst = null;
try
{
objUserMst = objdc.UserMsts.SingleOrDefault(Rec => Rec.UserMstID == strUserID);
if (objUserMst != null)
return true;
else
return false;
}
catch
{
throw;
}
finally
{

}
}



DataClassesDataContext is class name for DB.
UserMst is Table Name in DB

objdc.UserMsts.SingleOrDefault(Rec => Rec.UserMstID == strUserID);

The above method will check the username exists it will return the entire row if not exists it will return null

Aspx Code


First f = new First();
f.CheckUserExists(TextBox1.Text.Trim());


Complete Code Listing

First.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

///
/// Summary description for First
///

public class First
{
DataClassesDataContext objdc = null;
public First()
{
//
// TODO: Add constructor logic here
//
}
public bool CheckUserExists(string strUserID)
{
objdc = new DataClassesDataContext();
UserMst objUserMst = null;
try
{
objUserMst = objdc.UserMsts.SingleOrDefault(Rec => Rec.UserMstID == strUserID);
if (objUserMst != null)
return true;
else
return false;
}
catch
{
throw;
}
finally
{

}
}
}



Aspx Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
First f = new First();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
f.CheckUserExists(TextBox1.Text.Trim());

}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: