Insert using linq to sql

When we insert using LINQ then your table must have primary key. So the table which I was using not contain primary key. So I added one more column name id in the table which is primary and auto generated (used identity). So I have to make following changes in the class which maps my table to object oriented language which is as follows:-

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


[Table(Name="prod_rep")]
public class Class1
{
    [Column]
    public int prod_year;
    [Column]
    public string dept;
    [Column]
    public int no_of_prod;

    //isdbgenerated is used for auto generated column which is identity
    [Column(IsPrimaryKey=true,IsDbGenerated=true)]
    public int id;
}

	
		

Insertion Code using LINQ

Now use the following code to insert data in the table:-

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

public partial class Insert_LINQ_To_SQL : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //create the object of data context class and pass the connection string
        DataContext dc = new DataContext("Data Source=ISHA-PC;Initial Catalog=TechAltum;Integrated Security=True");

        //create object of class which mapped the table in database
        Class1 cal_data = new Class1();

        //add data to be inserted
        cal_data.prod_year=Convert.ToInt32(TextBox1.Text);
        cal_data.dept = TextBox2.Text;
        cal_data.no_of_prod = Convert.ToInt32(TextBox3.Text);

        //add data into the data context class for insertion
        dc.GetTable<Class1>().InsertOnSubmit(cal_data);
        dc.SubmitChanges();
     
      
    }
}

		

Email Address

For any query you can send mail at info@techaltum.com
Thanks