Day: August 5, 2009

INSERT Data in to Sql server database with LINQ Part 2

INTRODUCTION
In part 1 I have explained how to create LINQ datasource. To access the part 1 click on the following link.In this part I will explain how to insert data in to sql server database using LINQ.

EXAMPLE
We will take example of employee form where employee details are entered. The form will look somewhat like this.

mainscreen

First create instance of your Linq datasource as shown below.

public static string conn = ConfigurationManager.ConnectionStrings[“SampleConnectionString”].ToString();
EmployeesDetailsDataContext DetailContext = new EmployeesDetailsDataContext(conn);

The below code is used to add details to the employee table.

private void AddDetails()
{
try
{
bool ECodeExist = DetailContext.Employees.Any(ec => ec.Emp_Code ==txtEmpId.Text.Trim());
if (ECodeExist)
{
errmsg.InnerText = “Employee Code already assigned to another employee”;
}
else
{
bool exists = DetailContext.Employees.Any(e => e.F_Name ==
txtFname.Text.Trim() && e.L_Name == txtLname.Text.Trim());
if (exists)
{
errmsg.InnerText = “Employee already exist”;
}
else
{
Employee tblemp = new Employee();
tblemp.Emp_Code = txtEmpId.Text.Trim();
tblemp.F_Name = txtFname.Text.Trim();
tblemp.L_Name = txtLname.Text.Trim();
tblemp.Country = Convert.ToInt32(ddlCountry.SelectedValue);
tblemp.State = Convert.ToInt32(ddlRegion.SelectedValue);
tblemp.City = Convert.ToInt32(ddlCity.SelectedValue);
tblemp.Designation = txtDes.Text.Trim();
tblemp.Address = txtAdd.Text.Trim();
uploadphoto();
if (FileUpload1.HasFile)
{
tblemp.Photo = FileUpload1.FileName;
}
else
{
tblemp.Photo = string.Empty;
}
DetailContext.Employees.InsertOnSubmit(tblemp);
DetailContext.SubmitChanges();
BindGrid();
ClearControls();
}
}
}
catch (Exception ex)
{
common.LogErrorMessage(ex);
}
}

The above code will check for the existing of employee code with the help of “Any” keyword.

If the employee code already exist it will show message that the record already exist otherwise it will add record to the database.

In the above code an instance of employee table is created and data is entered in to the table by accessing the employee table property.

At last employee table instance is added to InsertOnSubmit method of LINQ datasource and the changes are submited finally by SubmitChanges().

After that the above method is called on the click event of a submit button as shown below.

protected void btnAdd_Click(object sender, EventArgs e)
{
AddDetails();
}

That is how we insert record in to the database through LINQ.

In the next part i will show you to populate data in to the controls using LINQ.Click on the following link to go next part.