Wednesday, December 23, 2009

Working with LINQ and Web Application with Business logic

Here is the steps to create Linq project

Step- 1 Create Blank solution named LinqTest

Step- 2 Add New Class Library named LingTest.DataModel

Add DBML file and from server explorer bind server connection
Add tables, procedures to Dbml file

Step- 3 Add New Class Library named LinqTest.DataAccess

 Add Reference from project LingTest.DataModel
 Create new class called UserDataAccess
 Add following namespaces in UserDataAccess class

using System.Collections.Generic;
using System.Linq;
using LinqTest.DataModel;
using System.Data.SqlClient;
using System.Data.Linq;
 Create methods as follows

public class UserDataAccess
{
// is derived from LinqTest.Datamodel
LinqTestDataContext db;
// User is table object
public int InsertUser(User user)
{
db = new LinqTestDataContext();
int returnvalue = 0;
int? UserId = 0;
try
{
returnvalue = db.Usp_InsertUser(ref ReturnId,parameters……….);
return Convert.ToInt32(UserId);
}
catch (Exception ex)
{
throw ex;
}
}

// Usp_SelectAllResult is procedure name in database
public List GetAllUsers(string username)
{
try
{
using (db = new LinqTestDataContext())
{
var selectedUsers = db.Usp_SelectAll(username);
List lstUsers = new List(selectedUsers);
return lstUsers;
}
}
catch (SqlException ex)
{
throw new LinqTestException("Unable to Get Details . Please try After some time.", ex);
}
catch (LinqTestException)
{
throw;
}
catch (Exception ex)
{
throw ex;
}
}


Step- 4 create one web application called LinqTest.Web
 Add Reference from project LingTest.DataModel , LingTest.DataAccess
 Add following namespaces in UserDataAccess class
using System.Collections.Generic;
using System.Linq;
using LinqTest.DataModel;
using System.Data.SqlClient;
using System.Data.Linq;
LingTest.DataModel call following function to get data
public void BindGrid()
{
List list = new UserDomain().GetAllUsers(“ ”); gridname.DataSource = list;
gridname.DataBind();
}
public void InsertUser()
{
LinqTest.DataModel.User obj = new User();
obj.Username = "name";
obj.password="12345";
int retval = new UserDomain().InsertUser(obj);
BindGrid();
}