In this example you will see how Linq to SQL class and add a new record into database. You can generate Linq to SQL classes in the ASP.NET Framework 3.5 and earlier version of Framework. Let’s Start.
Step 1: Create a table in SQL Server and insert some data as shown below.
CREATE TABLE PATIENTT
(
ID BIGINT IDENTITY,
NAME NVARCHAR(200),
CONSTRAINT [PK_PATIENTT] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
)GO
INSERT INTO PATIENT(NAME) VALUES('AAMIR')
INSERT INTO PATIENT(NAME) VALUES('AWAIS')
INSERT INTO PATIENT(NAME) VALUES('AHMED')
INSERT INTO PATIENT(NAME) VALUES('NASIR')
INSERT INTO PATIENT(NAME) VALUES('JAWAD')
Step2: Create a web site in Visual Studio 2010.
Step 3: Right click in the Web Site and click Add New Item, Create LINQ to SQL file in Web Site as shown below.

Step 4: Select Visual C#/Visual Basic from Installed Templates. Find LINQ to SQL Classes from Add New Item. Enter Patient.dbml and click Add button.

Step 5: From Server Explorer add your database and expand Tables node. Drag and Drop Patient table to Patient.dbml file. Save and close the file.

Step 6: Open Default.aspx.cs page and following code on page load as shown below.
protected void Page_Load(object sender, EventArgs e)
{
using (var db = new PatientDataContext())
{
var addPat = new PATIENT { NAME = "Hasan" };
db.PATIENTs.InsertOnSubmit(addPat);
db.SubmitChanges();
}
}
Note: Page should have using System.Linq reference at the top of page.
In the above code, I have created a new object of patient and fill the name value. Add the patient object to patient list and submitted the change to the patient table in the SQL Server database.
Note: table should have primary key otherwise it will through exception” System.InvalidOperationException: Can't perform Create, Update, or Delete operations on 'Table(PATIENT)' because it has no primary key.”
I hope this article will help you how to insert data in database using LINQ to SQL.
Download
insert-record-with-linq.rar (73.99 kb)